Repository navigation
Expand file tree
/
Copy pathcustom_json_handling.ts
More file actions
67 lines (61 loc) · 1.8 KB
/
Copy pathcustom_json_handling.ts
File metadata and controls
67 lines (61 loc) · 1.8 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
// Similar to `insert_js_dates.ts` but testing custom JSON handling
//
// JSON.stringify does not handle BigInt data types by default, so we'll provide
// a custom serializer before passing it to the JSON.stringify function.
//
// This example also shows how you can serialize Date objects in a custom way.
import { createClient } from "@clickhouse/client-web";
const valueSerializer = (value: unknown): unknown => {
if (value instanceof Date) {
// if you would have put this in the `replacer` parameter of JSON.stringify, (e.x: JSON.stringify(obj, replacerFn))
// it would have been an ISO string, but since we are serializing before `stringify`ing,
// it will convert it before the `.toJSON()` method has been called
return value.getTime();
}
if (typeof value === "bigint") {
return value.toString();
}
if (Array.isArray(value)) {
return value.map(valueSerializer);
}
if (typeof value === "object" && value !== null) {
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, valueSerializer(v)]),
);
}
return value;
};
const tableName = "inserts_custom_json_handling_web";
const client = createClient({
json: {
parse: JSON.parse,
stringify: (obj: unknown) => JSON.stringify(valueSerializer(obj)),
},
});
await client.command({
query: `DROP TABLE IF EXISTS ${tableName}`,
});
await client.command({
query: `
CREATE TABLE ${tableName}
(id UInt64, dt DateTime64(3, 'UTC'))
ENGINE MergeTree()
ORDER BY (id)
`,
});
await client.insert({
table: tableName,
values: [
{
id: BigInt(250000000000000200),
dt: new Date(),
},
],
format: "JSONEachRow",
});
const rows = await client.query({
query: `SELECT * FROM ${tableName}`,
format: "JSONEachRow",
});
console.info(await rows.json());
await client.close();