-
Notifications
You must be signed in to change notification settings - Fork 0
/
converter.ts
72 lines (65 loc) · 1.52 KB
/
converter.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
import {
ColumnProps,
CoreEntity,
EntityConfig,
EUpDateProperties,
} from '@grandlinex/core';
export function convertSpecialFields<E>(
meta: ColumnProps,
clone: any,
key: keyof E,
params: any[]
) {
if (meta.dataType === 'json') {
params.push(JSON.stringify(clone[key]));
} else {
params.push(clone[key]);
}
}
export function objToTable<E extends CoreEntity>(
config: EntityConfig<E>,
entity: E | EUpDateProperties<E>,
update?: boolean
): [(keyof E)[], string[], unknown[]] {
const clone: any = entity;
const keysOrigal = Object.keys(entity) as (keyof E)[];
const keys: (keyof E)[] = [];
const params: any[] = [];
const values: string[] = [];
let pCount = 1;
keysOrigal.forEach((key) => {
const meta = config.meta.get(key);
if (!meta) {
throw new Error('No col meta');
}
if (meta.primaryKey && update) {
return;
}
convertSpecialFields<E>(meta, clone, key, params);
if (update) {
values.push(`${String(key)}=$${pCount}`);
} else {
values.push(`$${pCount}`);
}
pCount += 1;
keys.push(key);
});
if (values.length === params.length && params.length === keys.length) {
return [keys, values, params];
}
throw new Error('Invalid output length');
}
export function rowToObj<E extends CoreEntity>(
config: EntityConfig<E>,
row: any
): E {
return row;
}
export function tableToObj<E extends CoreEntity>(
config: EntityConfig<E>,
table: any[]
): E[] {
return table.map((row) => {
return rowToObj(config, row);
});
}