-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathapi.v1.query.ts
More file actions
77 lines (66 loc) · 1.98 KB
/
api.v1.query.ts
File metadata and controls
77 lines (66 loc) · 1.98 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
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";
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"),
});
const { action, loader } = createActionApiRoute(
{
body: BodySchema,
corsStrategy: "all",
},
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 };