-
-
Notifications
You must be signed in to change notification settings - Fork 495
/
ObjectHydrator.ts
343 lines (283 loc) · 14.5 KB
/
ObjectHydrator.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import type { EntityData, EntityMetadata, EntityProperty } from '../typings';
import { Hydrator } from './Hydrator';
import { Collection } from '../entity/Collection';
import { Reference } from '../entity/Reference';
import { Utils } from '../utils/Utils';
import { ReferenceType } from '../enums';
import type { EntityFactory } from '../entity/EntityFactory';
type EntityHydrator<T> = (entity: T, data: EntityData<T>, factory: EntityFactory, newEntity: boolean, convertCustomTypes: boolean, schema?: string) => void;
export class ObjectHydrator extends Hydrator {
private readonly hydrators = {
full: new Map<string, EntityHydrator<any>>(),
reference: new Map<string, EntityHydrator<any>>(),
returning: new Map<string, EntityHydrator<any>>(),
};
private tmpIndex = 0;
/**
* @inheritDoc
*/
hydrate<T>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, type: 'full' | 'returning' | 'reference', newEntity = false, convertCustomTypes = false, schema?: string): void {
const hydrate = this.getEntityHydrator(meta, type);
Utils.callCompiledFunction(hydrate, entity, data, factory, newEntity, convertCustomTypes, schema);
}
/**
* @inheritDoc
*/
hydrateReference<T>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, factory: EntityFactory, convertCustomTypes = false, schema?: string): void {
const hydrate = this.getEntityHydrator(meta, 'reference');
Utils.callCompiledFunction(hydrate, entity, data, factory, false, convertCustomTypes, schema);
}
/**
* @internal Highly performance-sensitive method.
*/
getEntityHydrator<T>(meta: EntityMetadata<T>, type: 'full' | 'returning' | 'reference'): EntityHydrator<T> {
const exists = this.hydrators[type].get(meta.className);
if (exists) {
return exists;
}
const lines: string[] = [];
const context = new Map<string, any>();
const props = this.getProperties(meta, type);
context.set('isPrimaryKey', Utils.isPrimaryKey);
context.set('Collection', Collection);
context.set('Reference', Reference);
const preCondition = (dataKey: string) => {
/* istanbul ignore next */
const path = dataKey.match(/\[[^\]]+]|\.\w+/g) ?? [];
path.pop();
if (path.length === 0) {
return '';
}
let ret = '';
let prev = '';
for (const p of path) {
const key = prev ? prev + p : p;
ret += `data${key} && `;
prev = key;
}
return ret;
};
const hydrateScalar = <T, U>(prop: EntityProperty<T>, object: boolean | undefined, path: string[], dataKey: string): string[] => {
const entityKey = path.map(k => this.wrap(k)).join('');
const preCond = preCondition(dataKey);
const convertorKey = path.filter(k => !k.match(/\[idx_\d+]/)).map(k => this.safeKey(k)).join('_');
const ret: string[] = [];
if (prop.type.toLowerCase() === 'date') {
ret.push(
` if (${preCond}data${dataKey}) entity${entityKey} = new Date(data${dataKey});`,
` else if (${preCond}data${dataKey} === null) entity${entityKey} = null;`,
);
} else if (prop.customType) {
context.set(`convertToJSValue_${convertorKey}`, (val: any) => prop.customType.convertToJSValue(val, this.platform));
context.set(`convertToDatabaseValue_${convertorKey}`, (val: any) => prop.customType.convertToDatabaseValue(val, this.platform, { mode: 'hydration' }));
ret.push(
` if (${preCond}typeof data${dataKey} !== 'undefined') {`,
` if (convertCustomTypes) {`,
` const value = convertToJSValue_${convertorKey}(data${dataKey});`,
` data${dataKey} = convertToDatabaseValue_${convertorKey}(value);`, // make sure the value is comparable
` entity${entityKey} = value;`,
` } else {`,
` entity${entityKey} = data${dataKey};`,
` }`,
` }`,
);
} else if (prop.type.toLowerCase() === 'boolean') {
ret.push(` if (${preCond}typeof data${dataKey} !== 'undefined') entity${entityKey} = data${dataKey} === null ? null : !!data${dataKey};`);
} else {
ret.push(` if (${preCond}typeof data${dataKey} !== 'undefined') entity${entityKey} = data${dataKey};`);
}
return ret;
};
const hydrateToOne = (prop: EntityProperty, dataKey: string, entityKey: string) => {
const ret: string[] = [];
ret.push(` if (data${dataKey} === null) {\n entity${entityKey} = null;`);
ret.push(` } else if (typeof data${dataKey} !== 'undefined') {`);
ret.push(` if (isPrimaryKey(data${dataKey}, true)) {`);
if (prop.mapToPk) {
ret.push(` entity${entityKey} = data${dataKey};`);
} else if (prop.wrappedReference) {
ret.push(` entity${entityKey} = Reference.create(factory.createReference('${prop.type}', data${dataKey}, { merge: true, convertCustomTypes, schema }));`);
} else {
ret.push(` entity${entityKey} = factory.createReference('${prop.type}', data${dataKey}, { merge: true, convertCustomTypes, schema });`);
}
ret.push(` } else if (data${dataKey} && typeof data${dataKey} === 'object') {`);
if (prop.mapToPk) {
ret.push(` entity${entityKey} = data${dataKey};`);
} else if (prop.wrappedReference) {
ret.push(` entity${entityKey} = Reference.create(factory.create('${prop.type}', data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, schema }));`);
} else {
ret.push(` entity${entityKey} = factory.create('${prop.type}', data${dataKey}, { initialized: true, merge: true, newEntity, convertCustomTypes, schema });`);
}
ret.push(` }`);
ret.push(` }`);
if (prop.reference === ReferenceType.ONE_TO_ONE && !prop.mapToPk) {
const meta2 = this.metadata.get(prop.type);
const prop2 = meta2.properties[prop.inversedBy || prop.mappedBy];
if (prop2 && !prop2.mapToPk) {
ret.push(` if (entity${entityKey} && !entity${entityKey}.${prop2.name}) {`);
ret.push(` entity${entityKey}.${prop.wrappedReference ? 'unwrap().' : ''}${prop2.name} = ${prop2.wrappedReference ? 'Reference.create(entity)' : 'entity'};`);
ret.push(` }`);
}
}
if (prop.customType) {
context.set(`convertToDatabaseValue_${this.safeKey(prop.name)}`, (val: any) => prop.customType.convertToDatabaseValue(val, this.platform, { mode: 'hydration' }));
ret.push(` if (data${dataKey} != null && convertCustomTypes) {`);
ret.push(` data${dataKey} = convertToDatabaseValue_${this.safeKey(prop.name)}(entity${entityKey}.__helper.getPrimaryKey());`); // make sure the value is comparable
ret.push(` }`);
}
return ret;
};
const hydrateToMany = (prop: EntityProperty, dataKey: string, entityKey: string) => {
const ret: string[] = [];
ret.push(...this.createCollectionItemMapper(prop));
ret.push(` if (data${dataKey} && !Array.isArray(data${dataKey}) && typeof data${dataKey} === 'object') {`);
ret.push(` data${dataKey} = [data${dataKey}];`);
ret.push(` }`);
ret.push(` if (Array.isArray(data${dataKey})) {`);
ret.push(` const items = data${dataKey}.map(value => createCollectionItem_${this.safeKey(prop.name)}(value));`);
ret.push(` const coll = Collection.create(entity, '${prop.name}', items, newEntity);`);
ret.push(` if (newEntity) {`);
ret.push(` coll.setDirty();`);
ret.push(` } else {`);
ret.push(` coll.takeSnapshot(true);`);
ret.push(` }`);
ret.push(` } else if (!entity${entityKey} && data${dataKey} instanceof Collection) {`);
ret.push(` entity${entityKey} = data${dataKey};`);
ret.push(` } else if (!entity${entityKey}) {`);
const items = this.platform.usesPivotTable() || !prop.owner ? 'undefined' : '[]';
ret.push(` const coll = Collection.create(entity, '${prop.name}', ${items}, !!data${dataKey} || newEntity);`);
ret.push(` coll.setDirty(false);`);
ret.push(` }`);
return ret;
};
const registerEmbeddedPrototype = (prop: EntityProperty, path: string[]): void => {
const convertorKey = path.filter(k => !k.match(/\[idx_\d+]/)).map(k => this.safeKey(k)).join('_');
if (prop.targetMeta?.polymorphs) {
prop.targetMeta.polymorphs.forEach(meta => {
context.set(`prototype_${convertorKey}_${meta.className}`, meta.prototype);
});
} else {
context.set(`prototype_${convertorKey}`, prop.embeddable.prototype);
}
};
const parseObjectEmbeddable = (prop: EntityProperty, dataKey: string, ret: string[]): void => {
if (!this.platform.convertsJsonAutomatically() && (prop.object || prop.array)) {
ret.push(
` if (typeof data${dataKey} === 'string') {`,
` data${dataKey} = JSON.parse(data${dataKey});`,
` }`,
);
}
};
const hydrateEmbedded = (prop: EntityProperty, path: string[], dataKey: string): string[] => {
const entityKey = path.map(k => this.wrap(k)).join('');
const ret: string[] = [];
const conds: string[] = [];
registerEmbeddedPrototype(prop, path);
parseObjectEmbeddable(prop, dataKey, ret);
if (prop.object) {
conds.push(`data${dataKey} != null`);
} else {
const notNull = prop.nullable ? '!= null' : '!== undefined';
meta.props
.filter(p => p.embedded?.[0] === prop.name)
.forEach(p => conds.push(`data${this.wrap(p.name)} ${notNull}`));
}
ret.push(` if (${conds.join(' || ')}) {`);
if (prop.targetMeta?.polymorphs) {
prop.targetMeta.polymorphs!.forEach(meta => {
const childProp = prop.embeddedProps[prop.targetMeta!.discriminatorColumn!];
const childDataKey = prop.object ? dataKey + this.wrap(childProp.embedded![1]) : this.wrap(childProp.name);
// weak comparison as we can have numbers that might have been converted to strings due to being object keys
ret.push(` if (data${childDataKey} == '${meta.discriminatorValue}' && entity${entityKey} == null) {`);
ret.push(` entity${entityKey} = factory.createEmbeddable('${meta.className}', data${prop.object ? dataKey : ''}, { newEntity, convertCustomTypes });`);
ret.push(` }`);
});
} else {
ret.push(` if (entity${entityKey} == null) {`);
ret.push(` entity${entityKey} = factory.createEmbeddable('${prop.targetMeta!.className}', data${prop.object ? dataKey : ''}, { newEntity, convertCustomTypes });`);
ret.push(` }`);
}
meta.props
.filter(p => p.embedded?.[0] === prop.name)
.forEach(childProp => {
const childDataKey = prop.object ? dataKey + this.wrap(childProp.embedded![1]) : this.wrap(childProp.name);
// eslint-disable-next-line @typescript-eslint/no-use-before-define
ret.push(...hydrateProperty(childProp, prop.object, [...path, childProp.embedded![1]], childDataKey).map(l => ' ' + l));
});
/* istanbul ignore next */
const nullVal = this.config.get('forceUndefined') ? 'undefined' : 'null';
ret.push(` } else if (data${dataKey} === null) {`);
ret.push(` entity${entityKey} = ${nullVal};`);
ret.push(` }`);
return ret;
};
const hydrateEmbeddedArray = (prop: EntityProperty, path: string[], dataKey: string): string[] => {
const entityKey = path.map(k => this.wrap(k)).join('');
const ret: string[] = [];
const idx = this.tmpIndex++;
registerEmbeddedPrototype(prop, path);
parseObjectEmbeddable(prop, dataKey, ret);
ret.push(` if (Array.isArray(data${dataKey})) {`);
ret.push(` entity${entityKey} = [];`);
ret.push(` data${dataKey}.forEach((_, idx_${idx}) => {`);
ret.push(...hydrateEmbedded(prop, [...path, `[idx_${idx}]`], `${dataKey}[idx_${idx}]`).map(l => ' ' + l));
ret.push(` });`);
ret.push(` }`);
return ret;
};
const hydrateProperty = (prop: EntityProperty, object = prop.object, path: string[] = [prop.name], dataKey?: string): string[] => {
const entityKey = path.map(k => this.wrap(k)).join('');
dataKey = dataKey ?? (object ? entityKey : this.wrap(prop.name));
const ret: string[] = [];
if (prop.reference === ReferenceType.MANY_TO_ONE || prop.reference === ReferenceType.ONE_TO_ONE) {
ret.push(...hydrateToOne(prop, dataKey, entityKey));
} else if (prop.reference === ReferenceType.ONE_TO_MANY || prop.reference === ReferenceType.MANY_TO_MANY) {
ret.push(...hydrateToMany(prop, dataKey, entityKey));
} else if (prop.reference === ReferenceType.EMBEDDED) {
if (prop.array) {
ret.push(...hydrateEmbeddedArray(prop, path, dataKey));
} else {
ret.push(...hydrateEmbedded(prop, path, dataKey));
if (!prop.object) {
ret.push(...hydrateEmbedded({ ...prop, object: true }, path, dataKey));
}
}
} else { // ReferenceType.SCALAR
ret.push(...hydrateScalar(prop, object, path, dataKey));
}
if (this.config.get('forceUndefined')) {
ret.push(` if (data${dataKey} === null) entity${entityKey} = undefined;`);
}
return ret;
};
for (const prop of props) {
lines.push(...hydrateProperty(prop));
}
const code = `// compiled hydrator for entity ${meta.className} (${type})\n`
+ `return function(entity, data, factory, newEntity, convertCustomTypes, schema) {\n`
+ `${lines.join('\n')}\n}`;
const hydrator = Utils.createFunction(context, code);
this.hydrators[type].set(meta.className, hydrator);
return hydrator;
}
private createCollectionItemMapper<T>(prop: EntityProperty): string[] {
const meta = this.metadata.get(prop.type);
const lines: string[] = [];
lines.push(` const createCollectionItem_${this.safeKey(prop.name)} = value => {`);
lines.push(` if (isPrimaryKey(value, ${meta.compositePK})) return factory.createReference('${prop.type}', value, { convertCustomTypes, schema, merge: true });`);
lines.push(` if (value && value.__entity) return value;`);
lines.push(` return factory.create('${prop.type}', value, { newEntity, convertCustomTypes, schema, merge: true });`);
lines.push(` }`);
return lines;
}
private wrap(key: string): string {
if (key.match(/^\[.*]$/)) {
return key;
}
return key.match(/^\w+$/) ? `.${key}` : `['${key}']`;
}
private safeKey(key: string): string {
return key.replace(/[^\w]/g, '_');
}
}