1 | import { |
2 | ClickHouseSettings, |
3 | createClient, |
4 | DataFormat, |
5 | QueryParams, |
6 | } from "@clickhouse/[email protected]"; |
7 |
|
8 | |
9 | * @param parse_into Name of the method that should be used to parse the results. |
10 | * |
11 | * @param format Format of the resulting dataset. Wrap the format name with `"` in the |
12 | * argument editor. |
13 | * |
14 | * @param clickhouse_settings ClickHouse settings that can be applied on query level. |
15 | * |
16 | * @param query_params Parameters for query binding. |
17 | * |
18 | * @param query_params AbortSignal instance to cancel a query in progress. |
19 | */ |
20 | type Clickhouse = { |
21 | host: string; |
22 | username: string; |
23 | password: string; |
24 | }; |
25 | export async function main( |
26 | auth: Clickhouse, |
27 | query: string, |
28 | parse_into: "json" | "text" = "json", |
29 | format?: DataFormat, |
30 | clickhouse_settings?: ClickHouseSettings, |
31 | query_params?: Record<string, unknown>, |
32 | abort_signal?: AbortSignal, |
33 | ) { |
34 | const client = createClient(removeObjectEmptyFields(auth)); |
35 |
|
36 | const params = removeObjectEmptyFields({ |
37 | query, |
38 | format, |
39 | clickhouse_settings, |
40 | query_params, |
41 | abort_signal, |
42 | }) as QueryParams; |
43 | const result = await client.query(params); |
44 | await client.close(); |
45 |
|
46 | return await result[parse_into](); |
47 | } |
48 |
|
49 | function removeObjectEmptyFields( |
50 | object?: Record<string, any>, |
51 | removeEmptyArraysAndObjects = true, |
52 | createNewObject = true, |
53 | ) { |
54 | if (!object || typeof object !== "object") return {} |
55 | const obj = createNewObject ? { ...object } : object |
56 | const emptyValues = [undefined, null, ""] |
57 | for (const key in obj) { |
58 | const value = obj[key] |
59 | if (emptyValues.includes(value)) { |
60 | delete obj[key] |
61 | } else if (typeof value === "object") { |
62 | if (Object.keys(value).length) { |
63 | obj[key] = removeObjectEmptyFields(value, removeEmptyArraysAndObjects, false) |
64 | } |
65 | if (!Object.keys(value).length && removeEmptyArraysAndObjects) { |
66 | delete obj[key] |
67 | } |
68 | } |
69 | } |
70 | return obj |
71 | } |
72 |
|