-
-
Notifications
You must be signed in to change notification settings - Fork 496
/
EntityFactory.ts
353 lines (273 loc) · 13.5 KB
/
EntityFactory.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
344
345
346
347
348
349
350
351
352
353
import { Utils } from '../utils/Utils';
import type { Dictionary, EntityData, EntityMetadata, EntityName, EntityProperty, New, Primary } from '../typings';
import type { EntityManager } from '../EntityManager';
import { QueryHelper } from '../utils/QueryHelper';
import { EventType, ReferenceType } from '../enums';
import { Reference } from './Reference';
import { helper } from './wrap';
import type { EntityComparator } from '../utils/EntityComparator';
export interface FactoryOptions {
initialized?: boolean;
newEntity?: boolean;
merge?: boolean;
refresh?: boolean;
convertCustomTypes?: boolean;
schema?: string;
}
export class EntityFactory {
private readonly driver = this.em.getDriver();
private readonly platform = this.driver.getPlatform();
private readonly config = this.em.config;
private readonly metadata = this.em.getMetadata();
private readonly hydrator = this.config.getHydrator(this.metadata);
private readonly eventManager = this.em.getEventManager();
private readonly comparator = this.em.getComparator();
constructor(private readonly em: EntityManager) { }
create<T extends object, P extends string = string>(entityName: EntityName<T>, data: EntityData<T>, options: FactoryOptions = {}): New<T, P> {
data = Reference.unwrapReference(data);
options.initialized ??= true;
if ((data as Dictionary).__entity) {
return data as New<T, P>;
}
entityName = Utils.className(entityName);
const meta = this.metadata.get(entityName);
if (meta.virtual) {
data = { ...data };
const entity = this.createEntity<T>(data, meta, options);
this.hydrate(entity, meta, data, options);
return entity as New<T, P>;
}
if (this.platform.usesDifferentSerializedPrimaryKey()) {
meta.primaryKeys.forEach(pk => this.denormalizePrimaryKey(data, pk, meta.properties[pk]));
}
const meta2 = this.processDiscriminatorColumn<T>(meta, data);
const exists = this.findEntity<T>(data, meta2, options);
let wrapped = exists && helper(exists);
if (wrapped && !options.refresh) {
wrapped.__processing = true;
this.mergeData(meta2, exists!, data, options);
wrapped.__processing = false;
if (wrapped.isInitialized()) {
return exists as New<T, P>;
}
}
data = { ...data };
const entity = exists ?? this.createEntity<T>(data, meta2, options);
wrapped = helper(entity);
wrapped.__processing = true;
wrapped.__initialized = options.initialized;
this.hydrate(entity, meta2, data, options);
wrapped.__touched = false;
if (exists && meta.discriminatorColumn && !(entity instanceof meta2.class)) {
Object.setPrototypeOf(entity, meta2.prototype as object);
}
if (options.merge && wrapped.hasPrimaryKey()) {
this.unitOfWork.registerManaged(entity, data, {
refresh: options.refresh && options.initialized,
newEntity: options.newEntity,
loaded: options.initialized,
});
}
if (this.eventManager.hasListeners(EventType.onInit, meta2)) {
this.eventManager.dispatchEvent(EventType.onInit, { entity, em: this.em });
}
wrapped.__processing = false;
return entity as New<T, P>;
}
mergeData<T extends object>(meta: EntityMetadata<T>, entity: T, data: EntityData<T>, options: FactoryOptions = {}): void {
// merge unchanged properties automatically
data = QueryHelper.processParams({ ...data });
const existsData = this.comparator.prepareEntity(entity);
const originalEntityData = helper(entity).__originalEntityData ?? {} as EntityData<T>;
const diff = this.comparator.diffEntities(meta.className, originalEntityData, existsData);
// version properties are not part of entity snapshots
if (meta.versionProperty && data[meta.versionProperty as string] && data[meta.versionProperty as string] !== originalEntityData[meta.versionProperty as string]) {
diff[meta.versionProperty as string] = data[meta.versionProperty as string];
}
const diff2 = this.comparator.diffEntities(meta.className, existsData, data);
// do not override values changed by user
Object.keys(diff).forEach(key => delete diff2[key]);
Object.keys(diff2).filter(key => diff2[key] === undefined).forEach(key => delete diff2[key]);
// but always add collection properties if they are part of the `data`
Object.keys(data).filter(key => [ReferenceType.ONE_TO_MANY, ReferenceType.MANY_TO_MANY].includes(meta.properties[key]?.reference)).forEach(key => diff2[key] = data[key]);
// rehydrated with the new values, skip those changed by user
this.hydrate(entity, meta, diff2, options);
// we need to update the entity data only with keys that were not present before
Object.keys(diff2).forEach(key => {
const prop = meta.properties[key];
if ([ReferenceType.MANY_TO_ONE, ReferenceType.ONE_TO_ONE].includes(prop.reference) && Utils.isPlainObject(data[prop.name])) {
diff2[key] = helper(entity[prop.name]).getPrimaryKey(options.convertCustomTypes);
}
originalEntityData[key] = diff2[key];
helper(entity).__loadedProperties.add(key);
});
// in case of joined loading strategy, we need to cascade the merging to possibly loaded relations manually
meta.relations.forEach(prop => {
if ([ReferenceType.MANY_TO_MANY, ReferenceType.ONE_TO_MANY].includes(prop.reference) && Array.isArray(data[prop.name as string])) {
// instead of trying to match the collection items (which could easily fail if the collection was loaded with different ordering),
// we just create the entity from scratch, which will automatically pick the right one from the identity map and call `mergeData` on it
(data[prop.name as string] as EntityData<T>[])
.filter(child => Utils.isPlainObject(child)) // objects with prototype can be PKs (e.g. `ObjectId`)
.forEach(child => this.create(prop.type, child, options)); // we can ignore the value, we just care about the `mergeData` call
return;
}
if ([ReferenceType.MANY_TO_ONE, ReferenceType.ONE_TO_ONE].includes(prop.reference) && Utils.isPlainObject(data[prop.name as string]) && entity[prop.name] && helper(entity[prop.name]).__initialized) {
this.create(prop.type, data[prop.name as string] as EntityData<T>, options); // we can ignore the value, we just care about the `mergeData` call
}
});
helper(entity).__touched = false;
}
createReference<T extends object>(entityName: EntityName<T>, id: Primary<T> | Primary<T>[] | Record<string, Primary<T>>, options: Pick<FactoryOptions, 'merge' | 'convertCustomTypes' | 'schema'> = {}): T {
options.convertCustomTypes ??= true;
entityName = Utils.className(entityName);
const meta = this.metadata.get<T>(entityName);
const schema = this.driver.getSchemaName(meta, options);
if (Array.isArray(id)) {
// composite FK as PK needs to be wrapped for `getPrimaryKeyCondFromArray` to work correctly
if (!meta.compositePK && meta.getPrimaryProps()[0].reference !== ReferenceType.SCALAR) {
id = [id] as Primary<T>[];
}
id = Utils.getPrimaryKeyCondFromArray(id, meta);
}
const pks = Utils.getOrderedPrimaryKeys<T>(id, meta, this.platform, options.convertCustomTypes);
const exists = this.unitOfWork.getById<T>(entityName, pks as Primary<T>, schema);
if (exists) {
return exists;
}
if (Utils.isPrimaryKey(id)) {
id = { [meta.primaryKeys[0]]: id as Primary<T> };
}
return this.create<T>(entityName, id as EntityData<T>, { ...options, initialized: false }) as T;
}
createEmbeddable<T extends object>(entityName: EntityName<T>, data: EntityData<T>, options: Pick<FactoryOptions, 'newEntity' | 'convertCustomTypes'> = {}): T {
entityName = Utils.className(entityName);
data = { ...data };
const meta = this.metadata.get(entityName);
const meta2 = this.processDiscriminatorColumn<T>(meta, data);
return this.createEntity(data, meta2, options);
}
getComparator(): EntityComparator {
return this.comparator;
}
private createEntity<T extends object>(data: EntityData<T>, meta: EntityMetadata<T>, options: FactoryOptions): T {
if (options.newEntity || meta.forceConstructor || meta.virtual) {
if (!meta.class) {
throw new Error(`Cannot create entity ${meta.className}, class prototype is unknown`);
}
options.initialized = options.newEntity || options.initialized;
const params = this.extractConstructorParams<T>(meta, data, options);
const Entity = meta.class;
meta.constructorParams.forEach(prop => delete data[prop]);
// creates new instance via constructor as this is the new entity
const entity = new Entity(...params);
if (meta.virtual) {
return entity;
}
helper(entity).__schema = this.driver.getSchemaName(meta, options);
if (!options.newEntity) {
meta.relations
.filter(prop => [ReferenceType.ONE_TO_MANY, ReferenceType.MANY_TO_MANY].includes(prop.reference))
.forEach(prop => delete entity[prop.name]);
if (options.initialized && !(entity as Dictionary).__gettersDefined) {
Object.defineProperties(entity, meta.definedProperties);
}
}
return entity;
}
// creates new entity instance, bypassing constructor call as its already persisted entity
const entity = Object.create(meta.class.prototype) as T;
helper(entity).__managed = true;
helper(entity).__processing = !meta.embeddable && !meta.virtual;
helper(entity).__schema = this.driver.getSchemaName(meta, options);
if (options.merge && !options.newEntity) {
this.hydrator.hydrateReference(entity, meta, data, this, options.convertCustomTypes, this.driver.getSchemaName(meta, options));
this.unitOfWork.registerManaged(entity);
}
if (options.initialized && !(entity as Dictionary).__gettersDefined) {
Object.defineProperties(entity, meta.definedProperties);
}
return entity;
}
private hydrate<T extends object>(entity: T, meta: EntityMetadata<T>, data: EntityData<T>, options: FactoryOptions): void {
if (options.initialized) {
this.hydrator.hydrate(entity, meta, data, this, 'full', options.newEntity, options.convertCustomTypes, this.driver.getSchemaName(meta, options));
} else {
this.hydrator.hydrateReference(entity, meta, data, this, options.convertCustomTypes, this.driver.getSchemaName(meta, options));
}
Object.keys(data).forEach(key => helper(entity)?.__loadedProperties.add(key));
}
private findEntity<T extends object>(data: EntityData<T>, meta: EntityMetadata<T>, options: FactoryOptions): T | undefined {
const schema = this.driver.getSchemaName(meta, options);
if (meta.simplePK) {
return this.unitOfWork.getById<T>(meta.name!, data[meta.primaryKeys[0] as string] as Primary<T>, schema);
}
if (meta.primaryKeys.some(pk => data[pk as string] == null)) {
return undefined;
}
const pks = Utils.getOrderedPrimaryKeys<T>(data as Dictionary, meta, this.platform, options.convertCustomTypes);
return this.unitOfWork.getById<T>(meta.name!, pks, schema);
}
private processDiscriminatorColumn<T extends object>(meta: EntityMetadata<T>, data: EntityData<T>): EntityMetadata<T> {
if (!meta.root.discriminatorColumn) {
return meta;
}
const prop = meta.properties[meta.root.discriminatorColumn];
const value = data[prop.name];
const type = meta.root.discriminatorMap![value];
meta = type ? this.metadata.find(type)! : meta;
// `prop.userDefined` is either `undefined` or `false`
if (prop.userDefined === false) {
delete data[prop.name];
}
return meta;
}
/**
* denormalize PK to value required by driver (e.g. ObjectId)
*/
private denormalizePrimaryKey<T>(data: EntityData<T>, primaryKey: string, prop: EntityProperty<T>): void {
const pk = this.platform.getSerializedPrimaryKeyField(primaryKey);
if (data[pk] != null || data[primaryKey] != null) {
let id = data[pk] || data[primaryKey];
if (prop.type.toLowerCase() === 'objectid') {
id = this.platform.denormalizePrimaryKey(id);
}
delete data[pk];
data[primaryKey] = id as Primary<T> & T[keyof T];
}
}
/**
* returns parameters for entity constructor, creating references from plain ids
*/
private extractConstructorParams<T>(meta: EntityMetadata<T>, data: EntityData<T>, options: FactoryOptions): T[keyof T][] {
return meta.constructorParams.map(k => {
if (meta.properties[k] && [ReferenceType.MANY_TO_ONE, ReferenceType.ONE_TO_ONE].includes(meta.properties[k].reference) && data[k]) {
const entity = this.unitOfWork.getById(meta.properties[k].type, data[k], options.schema) as T[keyof T];
if (entity) {
return entity;
}
if (Utils.isEntity<T>(data[k])) {
return data[k];
}
if (Utils.isObject(data[k]) && !Utils.extractPK(data[k], meta.properties[k].targetMeta, true)) {
return this.create(meta.properties[k].type, data[k], options);
}
const { newEntity, initialized, ...rest } = options;
return this.createReference(meta.properties[k].type, data[k], rest);
}
if (meta.properties[k]?.reference === ReferenceType.EMBEDDED && data[k]) {
/* istanbul ignore next */
if (Utils.isEntity<T>(data[k])) {
return data[k];
}
return this.createEmbeddable(meta.properties[k].type, data[k], options);
}
if (!meta.properties[k]) {
return data;
}
return data[k];
});
}
private get unitOfWork() {
return this.em.getUnitOfWork(false);
}
}