-
Notifications
You must be signed in to change notification settings - Fork 0
/
converter.ts
96 lines (89 loc) · 2.1 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import {
ColumnProps,
CoreEntity,
EntityConfig,
EUpDateProperties,
} from '@grandlinex/core';
export function convertSpecialFields<E>(
meta: ColumnProps,
clone: any,
key: keyof E,
params: any[]
) {
switch (meta.dataType) {
case 'date':
if (clone[key] !== null) {
params.push((clone[key] as Date).toISOString());
} else {
params.push(null);
}
break;
case 'json':
params.push(JSON.stringify(clone[key]));
break;
case 'boolean':
params.push(clone[key] ? 1 : 0);
break;
default:
params.push(clone[key]);
break;
}
}
export function objToTable<E extends CoreEntity>(
entity: E | EUpDateProperties<E>,
config: EntityConfig<E>,
update?: boolean
): [(keyof E)[], string[], unknown[]] {
const clone: any = entity;
const keysOriginal = Object.keys(entity) as (keyof E)[];
const keys: (keyof E)[] = [];
const params: any[] = [];
const values: string[] = [];
keysOriginal.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)}=?`);
} else {
values.push(`?`);
}
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 {
const clone: any = row;
config.meta.forEach((value, key) => {
switch (value.dataType) {
case 'json':
clone[key] = clone[key] !== null ? JSON.parse(clone[key]) : null;
break;
case 'date':
clone[key] = clone[key] !== null ? new Date(clone[key]) : null;
break;
default:
break;
}
});
return clone;
}
export function tableToObj<E extends CoreEntity>(
config: EntityConfig<E>,
table: any[]
): E[] {
return table.map((row) => {
return rowToObj(config, row);
});
}