/
EntityHelper.ts
228 lines (195 loc) · 9.24 KB
/
EntityHelper.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
import { inspect } from 'util';
import type { EntityManager } from '../EntityManager';
import type { AnyEntity, Dictionary, EntityMetadata, EntityProperty, IHydrator } from '../typings';
import { EntityTransformer } from '../serialization/EntityTransformer';
import { Reference } from './Reference';
import { Utils } from '../utils/Utils';
import { WrappedEntity } from './WrappedEntity';
import { ReferenceType } from '../enums';
import { helper } from './wrap';
import { EntityRepositoryType, OptionalProps, PrimaryKeyProp, PrimaryKeyType } from '../typings';
export class EntityHelper {
static decorate<T extends object>(meta: EntityMetadata<T>, em: EntityManager): void {
const fork = em.fork(); // use fork so we can access `EntityFactory`
const serializedPrimaryKey = meta.props.find(p => p.serializedPrimaryKey);
if (serializedPrimaryKey) {
Object.defineProperty(meta.prototype, serializedPrimaryKey.name, {
get(): string | null {
return this._id ? em.getPlatform().normalizePrimaryKey<string>(this._id) : null;
},
set(id: string): void {
this._id = id ? em.getPlatform().denormalizePrimaryKey(id) : null;
},
});
}
EntityHelper.defineBaseProperties(meta, meta.prototype, fork);
if (!meta.embeddable && !meta.virtual) {
EntityHelper.defineProperties(meta, fork);
}
const prototype = meta.prototype as Dictionary;
if (!prototype.toJSON) { // toJSON can be overridden
prototype.toJSON = function (this: T, ...args: any[]) {
return EntityTransformer.toObject<T>(this, ...args.slice(meta.toJsonParams.length));
};
}
}
/**
* As a performance optimization, we create entity state methods in a lazy manner. We first add
* the `null` value to the prototype to reserve space in memory. Then we define a setter on the
* prototype, that will be executed exactly once per entity instance. There we redefine given
* property on the entity instance, so shadowing the prototype setter.
*/
private static defineBaseProperties<T extends object>(meta: EntityMetadata<T>, prototype: T, em: EntityManager) {
const helperParams = meta.embeddable || meta.virtual ? [] : [em.getComparator().getPkGetter(meta), em.getComparator().getPkSerializer(meta), em.getComparator().getPkGetterConverted(meta)];
Object.defineProperties(prototype, {
__entity: { value: !meta.embeddable },
__meta: { value: meta },
__platform: { value: em.getPlatform() },
__factory: { value: em.getEntityFactory() },
__helper: {
get(): WrappedEntity<T, keyof T> {
Object.defineProperty(this, '__helper', {
value: new WrappedEntity(this, em.getHydrator(), ...helperParams),
enumerable: false,
});
return this.__helper;
},
configurable: true, // otherwise jest fails when trying to compare entities ¯\_(ツ)_/¯
},
});
}
/**
* Defines getter and setter for every owning side of m:1 and 1:1 relation. This is then used for propagation of
* changes to the inverse side of bi-directional relations. Rest of the properties are also defined this way to
* achieve dirtiness, which is then used for fast checks whether we need to auto-flush because of managed entities.
*
* First defines a setter on the prototype, once called, actual get/set handlers are registered on the instance rather
* than on its prototype. Thanks to this we still have those properties enumerable (e.g. part of `Object.keys(entity)`).
*/
private static defineProperties<T>(meta: EntityMetadata<T>, em: EntityManager): void {
Object
.values<EntityProperty<T>>(meta.properties)
.forEach(prop => {
const isCollection = [ReferenceType.ONE_TO_MANY, ReferenceType.MANY_TO_MANY].includes(prop.reference);
const isReference = [ReferenceType.ONE_TO_ONE, ReferenceType.MANY_TO_ONE].includes(prop.reference) && (prop.inversedBy || prop.mappedBy) && !prop.mapToPk;
if (isReference) {
return Object.defineProperty(meta.prototype, prop.name, {
set(val: AnyEntity) {
EntityHelper.defineReferenceProperty(meta, prop, this, em.getHydrator());
this[prop.name] = val;
},
});
}
if (prop.inherited || prop.primary || prop.persist === false || prop.trackChanges === false || prop.embedded || isCollection) {
return;
}
Object.defineProperty(meta.prototype, prop.name, {
set(val) {
Object.defineProperty(this, prop.name, {
get() {
return this.__helper?.__data[prop.name];
},
set(val) {
this.__helper.__data[prop.name] = val;
this.__helper.__touched = true;
},
enumerable: true,
configurable: true,
});
this.__helper.__data[prop.name] = val;
this.__helper.__touched = true;
},
});
});
meta.prototype[inspect.custom] ??= function (this: T, depth: number) {
const object = { ...this };
// ensure we dont have internal symbols in the POJO
[OptionalProps, EntityRepositoryType, PrimaryKeyType, PrimaryKeyProp].forEach(sym => delete object[sym]);
const ret = inspect(object, { depth });
let name = (this as object).constructor.name;
const showEM = ['true', 't', '1'].includes(process.env.MIKRO_ORM_LOG_EM_ID?.toString().toLowerCase() ?? '');
if (showEM) {
if (helper(this).__em) {
name += ` [managed by ${helper(this).__em.id}]`;
} else {
name += ` [not managed]`;
}
}
// distinguish not initialized entities
if (!helper(this).__initialized) {
name = `(${name})`;
}
return ret === '[Object]' ? `[${name}]` : name + ' ' + ret;
};
}
static defineReferenceProperty<T extends object>(meta: EntityMetadata<T>, prop: EntityProperty<T>, ref: T, hydrator: IHydrator): void {
const wrapped = helper(ref);
Object.defineProperty(ref, prop.name, {
get() {
return helper(ref).__data[prop.name];
},
set(val: AnyEntity | Reference<AnyEntity>) {
const entity = Reference.unwrapReference(val ?? wrapped.__data[prop.name]);
const old = Reference.unwrapReference(wrapped.__data[prop.name]);
wrapped.__data[prop.name] = Reference.wrapReference(val as T, prop);
// when propagation from inside hydration, we set the FK to the entity data immediately
if (val && hydrator.isRunning() && wrapped.__originalEntityData && prop.owner) {
wrapped.__originalEntityData[prop.name as string] = helper(wrapped.__data[prop.name]).getPrimaryKey(true);
} else {
wrapped.__touched = true;
}
EntityHelper.propagate(meta, entity, this, prop, Reference.unwrapReference(val), old);
},
enumerable: true,
configurable: true,
});
}
static propagate<T extends object, O extends object>(meta: EntityMetadata<O>, entity: T, owner: O, prop: EntityProperty<O>, value?: T[keyof T & string], old?: object): void {
const inverseProps = prop.targetMeta!.bidirectionalRelations.filter(prop2 =>
(prop2.inversedBy || prop2.mappedBy) === prop.name
&& (
prop2.targetMeta!.abstract ?
prop2.targetMeta!.root.className === meta.root.className :
prop2.targetMeta!.className === meta.className
),
);
for (const prop2 of inverseProps) {
const inverse = value?.[prop2.name as string];
if (prop.reference === ReferenceType.MANY_TO_ONE && Utils.isCollection<O, T>(inverse) && inverse.isInitialized()) {
inverse.add(owner);
}
if (prop.reference === ReferenceType.ONE_TO_ONE && entity && helper(entity).__initialized) {
if (
(value != null && Reference.unwrapReference(inverse) !== owner) ||
(value == null && entity[prop2.name] != null)
) {
EntityHelper.propagateOneToOne(entity, owner, prop, prop2, value, old as T);
}
}
}
}
private static propagateOneToOne<T extends object, O extends object>(entity: T, owner: O, prop: EntityProperty<O>, prop2: EntityProperty<T>, value?: T[keyof T & string], old?: T): void {
helper(entity).__pk = helper(entity).getPrimaryKey()!;
// the inverse side will be changed on the `value` too, so we need to clean-up and schedule orphan removal there too
if (!prop.primary && !prop2.mapToPk && value?.[prop2.name as string] != null && Reference.unwrapReference(value[prop2.name as string]) !== entity) {
const other = Reference.unwrapReference(value[prop2.name as string]);
delete helper(other).__data[prop.name];
if (prop2.orphanRemoval) {
helper(other).__em?.getUnitOfWork().scheduleOrphanRemoval(other);
}
}
if (value == null) {
entity[prop2.name] = value as T[keyof T & string];
} else if (prop2.mapToPk) {
entity[prop2.name] = helper(owner).getPrimaryKey() as T[keyof T & string];
} else {
entity[prop2.name] = Reference.wrapReference(owner, prop) as T[keyof T & string];
}
if (old && prop.orphanRemoval) {
helper(old).__em?.getUnitOfWork().scheduleOrphanRemoval(old);
}
if (old?.[prop2.name] != null) {
delete helper(old).__data[prop2.name];
}
}
}