-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandleQuery.ts
73 lines (64 loc) · 2.63 KB
/
handleQuery.ts
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
import { Context } from "hono";
import { APIErrorResponse, computePagination } from "./utils.js";
import { makeQuery } from "./clickhouse/makeQuery.js";
import { DEFAULT_LIMIT, DEFAULT_PAGE } from "./config.js";
import { ApiErrorResponse, ApiUsageResponse, limitSchema, pageSchema } from "./types/zod.js";
export async function handleUsageQueryError(ctx: Context, result: ApiUsageResponse | ApiErrorResponse) {
if ('status' in result)
return APIErrorResponse(
ctx,
result.status,
result.code,
result.message
);
return ctx.json(result);
}
// backwards compatible
export async function makeUsageQuery(ctx: Context, query: string[], query_params: Record<string, string | number> = {}, database: string) {
const result = await makeUsageQueryJson(ctx, query, query_params, database);
return await handleUsageQueryError(ctx, result);
}
export async function makeUsageQueryJson<T = unknown>(
ctx: Context,
query: string[],
query_params: Record<string, string | number> = {},
database: string
): Promise<ApiUsageResponse | ApiErrorResponse> {
const limit = limitSchema.safeParse(ctx.req.query("limit")).data ?? DEFAULT_LIMIT;
query.push('LIMIT {limit: int}');
query_params.limit = limit;
const page = pageSchema.safeParse(ctx.req.query("page")).data ?? DEFAULT_PAGE;
query.push('OFFSET {offset: int}');
// Since `page` starts at 1, `offset` should be positive for page > 1
query_params.offset = query_params.limit * (page - 1);
// start of request
const request_time = new Date();
// inject request query params
query_params = { ...ctx.req.param(), ...ctx.req.query(), ...query_params };
try {
const result = await makeQuery<T>(query.join(" "), query_params, database);
if (result.data.length === 0) {
return {
status: 404 as ApiErrorResponse["status"],
code: "not_found_data" as ApiErrorResponse["code"],
message: 'No data found'
};
}
const total_results = result.rows_before_limit_at_least ?? 0;
return {
data: result.data,
statistics: result.statistics ?? {},
pagination: computePagination(page, limit, total_results),
results: result.rows ?? 0,
total_results,
request_time,
duration_ms: Number(new Date()) - Number(request_time),
};
} catch (err) {
return {
status: 500 as ApiErrorResponse["status"],
code: "bad_database_response" as ApiErrorResponse["code"],
message: `${err}`
};
}
}