-
-
Notifications
You must be signed in to change notification settings - Fork 496
/
Collection.ts
295 lines (240 loc) · 8.78 KB
/
Collection.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
import { AnyEntity, Dictionary, EntityData, FilterQuery, Primary } from '../typings';
import { ArrayCollection } from './index';
import { ReferenceType } from './enums';
import { Utils, ValidationError } from '../utils';
import { QueryOrder, QueryOrderMap } from '../enums';
import { Reference } from './Reference';
import { wrap } from './wrap';
export class Collection<T extends AnyEntity<T>, O extends AnyEntity<O> = AnyEntity> extends ArrayCollection<T, O> {
private snapshot: T[] | undefined = []; // used to create a diff of the collection at commit time
private initialized = false;
private dirty = false;
private _populated = false;
constructor(owner: O, items?: T[], initialized = true) {
super(owner, items);
this.initialized = !!items || initialized;
Object.defineProperty(this, 'snapshot', { enumerable: false });
Object.defineProperty(this, '_populated', { enumerable: false });
}
/**
* Creates new Collection instance, assigns it to the owning entity and sets the items to it (propagating them to their inverse sides)
*/
static create<T extends AnyEntity<T>, O extends AnyEntity<O> = AnyEntity>(owner: O, prop: keyof O, items: undefined | T[], initialized: boolean): Collection<T, O> {
const coll = new Collection<T, O>(owner, items, initialized);
owner[prop] = coll as unknown as O[keyof O];
if (items) {
coll.set(items);
}
return coll;
}
/**
* Initializes the collection and returns the items
*/
async loadItems(): Promise<T[]> {
if (!this.isInitialized(true)) {
await this.init();
}
return super.getItems();
}
/**
* Returns the items (the collection must be initialized)
*/
getItems(check = true): T[] {
if (check) {
this.checkInitialized();
}
return super.getItems();
}
add(...items: (T | Reference<T>)[]): void {
const unwrapped = items.map(i => Reference.unwrapReference(i));
unwrapped.map(item => this.validateItemType(item));
this.modify('add', unwrapped);
this.cancelOrphanRemoval(unwrapped);
}
set(items: (T | Reference<T>)[]): void {
const unwrapped = items.map(i => Reference.unwrapReference(i));
unwrapped.map(item => this.validateItemType(item));
this.validateModification(unwrapped);
super.set(unwrapped);
this.setDirty();
this.cancelOrphanRemoval(unwrapped);
}
/**
* @internal
*/
hydrate(items: T[], validate = false, takeSnapshot = true): void {
if (validate) {
this.validateModification(items);
}
const wasInitialized = this.initialized;
const wasDirty = this.dirty;
this.initialized = true;
super.hydrate(items);
this.dirty = wasDirty;
if (!wasInitialized) {
this.snapshot = undefined;
} else if (takeSnapshot) {
this.takeSnapshot();
}
}
remove(...items: (T | Reference<T>)[]): void {
const unwrapped = items.map(i => Reference.unwrapReference(i));
this.modify('remove', unwrapped);
const em = wrap(this.owner, true).__em;
if (this.property.orphanRemoval && em) {
for (const item of unwrapped) {
em.getUnitOfWork().scheduleOrphanRemoval(item);
}
}
}
contains(item: (T | Reference<T>), check = true): boolean {
if (check) {
this.checkInitialized();
}
return super.contains(item);
}
count(): number {
this.checkInitialized();
return super.count();
}
isInitialized(fully = false): boolean {
if (fully) {
return this.initialized && this.items.every(item => wrap(item, true).isInitialized());
}
return this.initialized;
}
shouldPopulate(): boolean {
return this._populated;
}
populated(populated = true): void {
this._populated = populated;
}
isDirty(): boolean {
return this.dirty;
}
setDirty(dirty = true): void {
this.dirty = dirty && !!this.property.owner; // set dirty flag only to owning side
}
async init(options?: InitOptions<T>): Promise<this>;
async init(populate?: string[], where?: FilterQuery<T>, orderBy?: QueryOrderMap): Promise<this>;
async init(populate: string[] | InitOptions<T> = [], where?: FilterQuery<T>, orderBy?: QueryOrderMap): Promise<this> {
const options = Utils.isObject<InitOptions<T>>(populate) ? populate : { populate, where, orderBy };
const em = wrap(this.owner, true).__em;
if (!em) {
throw ValidationError.entityNotManaged(this.owner);
}
if (!this.initialized && this.property.reference === ReferenceType.MANY_TO_MANY && em.getDriver().getPlatform().usesPivotTable()) {
const map = await em.getDriver().loadFromPivotTable<T, O>(this.property, [wrap(this.owner, true).__primaryKeys], options.where, options.orderBy);
this.hydrate(map[wrap(this.owner, true).__serializedPrimaryKey].map(item => em.merge<T>(this.property.type, item)));
return this;
}
// do not make db call if we know we will get no results
if (this.property.reference === ReferenceType.MANY_TO_MANY && (this.property.owner || em.getDriver().getPlatform().usesPivotTable()) && this.length === 0) {
this.initialized = true;
this.dirty = false;
this.populated();
return this;
}
where = this.createCondition<T>(options.where);
const order = [...this.items]; // copy order of references
const customOrder = !!options.orderBy;
orderBy = this.createOrderBy(options.orderBy);
const items = await em.find<T>(this.property.type, where, options.populate, orderBy);
if (!customOrder) {
this.reorderItems(items, order);
}
this.items.length = 0;
this.items.push(...items);
Object.assign(this, items);
this.initialized = true;
this.dirty = false;
this.populated();
return this;
}
/**
* @internal
*/
takeSnapshot(): void {
this.snapshot = [...this.items];
this.setDirty(false);
}
/**
* @internal
*/
getSnapshot() {
return this.snapshot;
}
private createCondition<T extends AnyEntity<T>>(cond: FilterQuery<T> = {}): FilterQuery<T> {
if (this.property.reference === ReferenceType.ONE_TO_MANY) {
cond[this.property.mappedBy as string] = wrap(this.owner, true).__primaryKey;
} else { // MANY_TO_MANY
this.createManyToManyCondition(cond as Dictionary);
}
return cond;
}
private createOrderBy(orderBy: QueryOrderMap = {}): QueryOrderMap {
if (Utils.isEmpty(orderBy) && this.property.reference === ReferenceType.ONE_TO_MANY) {
const defaultOrder = this.property.referencedColumnNames.reduce((o, name) => {
o[name] = QueryOrder.ASC;
return o;
}, {} as QueryOrderMap);
orderBy = this.property.orderBy || defaultOrder;
}
return orderBy;
}
private createManyToManyCondition(cond: Dictionary) {
if (this.property.owner || wrap(this.owner, true).__internal.platform.usesPivotTable()) {
const pk = wrap(this.items[0], true).__meta.primaryKeys[0]; // we know there is at least one item as it was checked in load method
cond[pk] = { $in: this.items.map(item => wrap(item, true).__primaryKey) };
} else {
cond[this.property.mappedBy] = wrap(this.owner, true).__primaryKey;
}
}
private modify(method: 'add' | 'remove', items: T[]): void {
if (method === 'remove') {
this.checkInitialized();
}
this.validateModification(items);
super[method](...items);
this.setDirty();
}
private checkInitialized(): void {
if (!this.isInitialized()) {
throw new Error(`Collection<${this.property.type}> of entity ${this.owner.constructor.name}[${wrap(this.owner, true).__primaryKey}] not initialized`);
}
}
/**
* re-orders items after searching with `$in` operator
*/
private reorderItems(items: T[], order: T[]): void {
if (this.property.reference === ReferenceType.MANY_TO_MANY && this.property.owner) {
items.sort((a, b) => order.indexOf(a) - order.indexOf(b));
}
}
private cancelOrphanRemoval(items: T[]): void {
const em = wrap(this.owner, true).__em;
if (!em) {
return;
}
for (const item of items) {
em!.getUnitOfWork().cancelOrphanRemoval(item);
}
}
private validateItemType(item: T | Primary<T> | EntityData<T>): void {
if (!Utils.isEntity(item)) {
throw ValidationError.notEntity(this.owner, this.property, item);
}
}
private validateModification(items: T[]): void {
// throw if we are modifying inverse side of M:N collection when owning side is initialized (would be ignored when persisting)
const manyToManyInverse = this.property.reference === ReferenceType.MANY_TO_MANY && this.property.mappedBy;
if (manyToManyInverse && items.find(item => !wrap(item, true).isInitialized() || !item[this.property.mappedBy])) {
throw ValidationError.cannotModifyInverseCollection(this.owner, this.property);
}
}
}
export interface InitOptions<T> {
populate?: string[];
orderBy?: QueryOrderMap;
where?: FilterQuery<T>;
}