-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathapi.v1.query.ts
More file actions
95 lines (83 loc) · 2.58 KB
/
api.v1.query.ts
File metadata and controls
95 lines (83 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { json } from "@remix-run/server-runtime";
import { QueryError } from "@internal/clickhouse";
import { z } from "zod";
import { createActionApiRoute } from "~/services/routeBuilders/apiBuilder.server";
import { executeQuery, type QueryScope } from "~/services/queryService.server";
import { logger } from "~/services/logger.server";
import { rowsToCSV } from "~/utils/dataExport";
import { querySchemas } from "~/v3/querySchemas";
const BodySchema = z.object({
query: z.string(),
scope: z.enum(["organization", "project", "environment"]).default("environment"),
period: z.string().nullish(),
from: z.string().nullish(),
to: z.string().nullish(),
format: z.enum(["json", "csv"]).default("json"),
});
/** Extract table names from a TRQL query for authorization */
function detectTables(query: string): string[] {
return querySchemas
.filter((s) => new RegExp(`\\bFROM\\s+${s.name}\\b`, "i").test(query))
.map((s) => s.name);
}
const { action, loader } = createActionApiRoute(
{
body: BodySchema,
allowJWT: true,
corsStrategy: "all",
findResource: async () => 1,
authorization: {
action: "read",
resource: (_, __, ___, body) => {
const tables = detectTables(body.query);
return { query: tables.length > 0 ? tables : "all" };
},
superScopes: ["read:query", "read:all", "admin"],
},
},
async ({ body, authentication }) => {
const { query, scope, period, from, to, format } = body;
const env = authentication.environment;
const queryResult = await executeQuery({
name: "api-query",
query,
scope: scope as QueryScope,
organizationId: env.organization.id,
projectId: env.project.id,
environmentId: env.id,
period,
from,
to,
history: {
source: "API",
},
});
if (!queryResult.success) {
const message =
queryResult.error instanceof QueryError
? queryResult.error.message
: "An unexpected error occurred while executing the query.";
logger.error("Query API error", {
error: queryResult.error,
query,
});
return json(
{ error: message },
{ status: queryResult.error instanceof QueryError ? 400 : 500 }
);
}
const { result, periodClipped, maxQueryPeriod } = queryResult;
if (format === "csv") {
const csv = rowsToCSV(result.rows, result.columns);
return json({
format: "csv",
results: csv,
});
}
return json({
format: "json",
results: result.rows,
});
}
);
export { action, loader };