-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
Repository.ts
647 lines (588 loc) · 19.8 KB
/
Repository.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
import { FindManyOptions } from "../find-options/FindManyOptions"
import { ObjectLiteral } from "../common/ObjectLiteral"
import { FindOneOptions } from "../find-options/FindOneOptions"
import { DeepPartial } from "../common/DeepPartial"
import { SaveOptions } from "./SaveOptions"
import { RemoveOptions } from "./RemoveOptions"
import { EntityManager } from "../entity-manager/EntityManager"
import { QueryRunner } from "../query-runner/QueryRunner"
import { SelectQueryBuilder } from "../query-builder/SelectQueryBuilder"
import { DeleteResult } from "../query-builder/result/DeleteResult"
import { UpdateResult } from "../query-builder/result/UpdateResult"
import { InsertResult } from "../query-builder/result/InsertResult"
import { QueryDeepPartialEntity } from "../query-builder/QueryPartialEntity"
import { ObjectID } from "../driver/mongodb/typings"
import { FindOptionsWhere } from "../find-options/FindOptionsWhere"
import { UpsertOptions } from "./UpsertOptions"
import { EntityTarget } from "../common/EntityTarget"
/**
* Repository is supposed to work with your entity objects. Find entities, insert, update, delete, etc.
*/
export class Repository<Entity extends ObjectLiteral> {
// -------------------------------------------------------------------------
// Public Properties
// -------------------------------------------------------------------------
/**
* Entity target that is managed by this repository.
* If this repository manages entity from schema,
* then it returns a name of that schema instead.
*/
readonly target: EntityTarget<Entity>
/**
* Entity Manager used by this repository.
*/
readonly manager: EntityManager
/**
* Query runner provider used for this repository.
*/
readonly queryRunner?: QueryRunner
// -------------------------------------------------------------------------
// Accessors
// -------------------------------------------------------------------------
/**
* Entity metadata of the entity current repository manages.
*/
get metadata() {
return this.manager.connection.getMetadata(this.target)
}
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(
target: EntityTarget<Entity>,
manager: EntityManager,
queryRunner?: QueryRunner,
) {
this.target = target
this.manager = manager
this.queryRunner = queryRunner
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Creates a new query builder that can be used to build a SQL query.
*/
createQueryBuilder(
alias?: string,
queryRunner?: QueryRunner,
): SelectQueryBuilder<Entity> {
return this.manager.createQueryBuilder<Entity>(
this.metadata.target as any,
alias || this.metadata.targetName,
queryRunner || this.queryRunner,
)
}
/**
* Checks if entity has an id.
* If entity composite compose ids, it will check them all.
*/
hasId(entity: Entity): boolean {
return this.manager.hasId(this.metadata.target, entity)
}
/**
* Gets entity mixed id.
*/
getId(entity: Entity): any {
return this.manager.getId(this.metadata.target, entity)
}
/**
* Creates a new entity instance.
*/
create(): Entity
/**
* Creates new entities and copies all entity properties from given objects into their new entities.
* Note that it copies only properties that are present in entity schema.
*/
create(entityLikeArray: DeepPartial<Entity>[]): Entity[]
/**
* Creates a new entity instance and copies all entity properties from this object into a new entity.
* Note that it copies only properties that are present in entity schema.
*/
create(entityLike: DeepPartial<Entity>): Entity
/**
* Creates a new entity instance or instances.
* Can copy properties from the given object into new entities.
*/
create(
plainEntityLikeOrPlainEntityLikes?:
| DeepPartial<Entity>
| DeepPartial<Entity>[],
): Entity | Entity[] {
return this.manager.create<any>(
this.metadata.target as any,
plainEntityLikeOrPlainEntityLikes as any,
)
}
/**
* Merges multiple entities (or entity-like objects) into a given entity.
*/
merge(
mergeIntoEntity: Entity,
...entityLikes: DeepPartial<Entity>[]
): Entity {
return this.manager.merge(
this.metadata.target as any,
mergeIntoEntity,
...entityLikes,
)
}
/**
* Creates a new entity from the given plain javascript object. If entity already exist in the database, then
* it loads it (and everything related to it), replaces all values with the new ones from the given object
* and returns this new entity. This new entity is actually a loaded from the db entity with all properties
* replaced from the new object.
*
* Note that given entity-like object must have an entity id / primary key to find entity by.
* Returns undefined if entity with given id was not found.
*/
preload(entityLike: DeepPartial<Entity>): Promise<Entity | undefined> {
return this.manager.preload(this.metadata.target as any, entityLike)
}
/**
* Saves all given entities in the database.
* If entities do not exist in the database then inserts, otherwise updates.
*/
save<T extends DeepPartial<Entity>>(
entities: T[],
options: SaveOptions & { reload: false },
): Promise<T[]>
/**
* Saves all given entities in the database.
* If entities do not exist in the database then inserts, otherwise updates.
*/
save<T extends DeepPartial<Entity>>(
entities: T[],
options?: SaveOptions,
): Promise<(T & Entity)[]>
/**
* Saves a given entity in the database.
* If entity does not exist in the database then inserts, otherwise updates.
*/
save<T extends DeepPartial<Entity>>(
entity: T,
options: SaveOptions & { reload: false },
): Promise<T>
/**
* Saves a given entity in the database.
* If entity does not exist in the database then inserts, otherwise updates.
*/
save<T extends DeepPartial<Entity>>(
entity: T,
options?: SaveOptions,
): Promise<T & Entity>
/**
* Saves one or many given entities.
*/
save<T extends DeepPartial<Entity>>(
entityOrEntities: T | T[],
options?: SaveOptions,
): Promise<T | T[]> {
return this.manager.save<Entity, T>(
this.metadata.target as any,
entityOrEntities as any,
options,
)
}
/**
* Removes a given entities from the database.
*/
remove(entities: Entity[], options?: RemoveOptions): Promise<Entity[]>
/**
* Removes a given entity from the database.
*/
remove(entity: Entity, options?: RemoveOptions): Promise<Entity>
/**
* Removes one or many given entities.
*/
remove(
entityOrEntities: Entity | Entity[],
options?: RemoveOptions,
): Promise<Entity | Entity[]> {
return this.manager.remove(
this.metadata.target as any,
entityOrEntities as any,
options,
)
}
/**
* Records the delete date of all given entities.
*/
softRemove<T extends DeepPartial<Entity>>(
entities: T[],
options: SaveOptions & { reload: false },
): Promise<T[]>
/**
* Records the delete date of all given entities.
*/
softRemove<T extends DeepPartial<Entity>>(
entities: T[],
options?: SaveOptions,
): Promise<(T & Entity)[]>
/**
* Records the delete date of a given entity.
*/
softRemove<T extends DeepPartial<Entity>>(
entity: T,
options: SaveOptions & { reload: false },
): Promise<T>
/**
* Records the delete date of a given entity.
*/
softRemove<T extends DeepPartial<Entity>>(
entity: T,
options?: SaveOptions,
): Promise<T & Entity>
/**
* Records the delete date of one or many given entities.
*/
softRemove<T extends DeepPartial<Entity>>(
entityOrEntities: T | T[],
options?: SaveOptions,
): Promise<T | T[]> {
return this.manager.softRemove<Entity, T>(
this.metadata.target as any,
entityOrEntities as any,
options,
)
}
/**
* Recovers all given entities in the database.
*/
recover<T extends DeepPartial<Entity>>(
entities: T[],
options: SaveOptions & { reload: false },
): Promise<T[]>
/**
* Recovers all given entities in the database.
*/
recover<T extends DeepPartial<Entity>>(
entities: T[],
options?: SaveOptions,
): Promise<(T & Entity)[]>
/**
* Recovers a given entity in the database.
*/
recover<T extends DeepPartial<Entity>>(
entity: T,
options: SaveOptions & { reload: false },
): Promise<T>
/**
* Recovers a given entity in the database.
*/
recover<T extends DeepPartial<Entity>>(
entity: T,
options?: SaveOptions,
): Promise<T & Entity>
/**
* Recovers one or many given entities.
*/
recover<T extends DeepPartial<Entity>>(
entityOrEntities: T | T[],
options?: SaveOptions,
): Promise<T | T[]> {
return this.manager.recover<Entity, T>(
this.metadata.target as any,
entityOrEntities as any,
options,
)
}
/**
* Inserts a given entity into the database.
* Unlike save method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient INSERT query.
* Does not check if entity exist in the database, so query will fail if duplicate entity is being inserted.
*/
insert(
entity:
| QueryDeepPartialEntity<Entity>
| QueryDeepPartialEntity<Entity>[],
): Promise<InsertResult> {
return this.manager.insert(this.metadata.target as any, entity)
}
/**
* Updates entity partially. Entity can be found by a given conditions.
* Unlike save method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient UPDATE query.
* Does not check if entity exist in the database.
*/
update(
criteria:
| string
| string[]
| number
| number[]
| Date
| Date[]
| ObjectID
| ObjectID[]
| FindOptionsWhere<Entity>,
partialEntity: QueryDeepPartialEntity<Entity>,
): Promise<UpdateResult> {
return this.manager.update(
this.metadata.target as any,
criteria as any,
partialEntity,
)
}
/**
* Inserts a given entity into the database, unless a unique constraint conflicts then updates the entity
* Unlike save method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient INSERT ... ON CONFLICT DO UPDATE/ON DUPLICATE KEY UPDATE query.
*/
upsert(
entityOrEntities:
| QueryDeepPartialEntity<Entity>
| QueryDeepPartialEntity<Entity>[],
conflictPathsOrOptions: string[] | UpsertOptions<Entity>,
): Promise<InsertResult> {
return this.manager.upsert(
this.metadata.target as any,
entityOrEntities,
conflictPathsOrOptions,
)
}
/**
* Deletes entities by a given criteria.
* Unlike save method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient DELETE query.
* Does not check if entity exist in the database.
*/
delete(
criteria:
| string
| string[]
| number
| number[]
| Date
| Date[]
| ObjectID
| ObjectID[]
| FindOptionsWhere<Entity>,
): Promise<DeleteResult> {
return this.manager.delete(this.metadata.target as any, criteria as any)
}
/**
* Records the delete date of entities by a given criteria.
* Unlike save method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient SOFT-DELETE query.
* Does not check if entity exist in the database.
*/
softDelete(
criteria:
| string
| string[]
| number
| number[]
| Date
| Date[]
| ObjectID
| ObjectID[]
| FindOptionsWhere<Entity>,
): Promise<UpdateResult> {
return this.manager.softDelete(
this.metadata.target as any,
criteria as any,
)
}
/**
* Restores entities by a given criteria.
* Unlike save method executes a primitive operation without cascades, relations and other operations included.
* Executes fast and efficient SOFT-DELETE query.
* Does not check if entity exist in the database.
*/
restore(
criteria:
| string
| string[]
| number
| number[]
| Date
| Date[]
| ObjectID
| ObjectID[]
| FindOptionsWhere<Entity>,
): Promise<UpdateResult> {
return this.manager.restore(
this.metadata.target as any,
criteria as any,
)
}
/**
* Counts entities that match given options.
* Useful for pagination.
*/
count(options?: FindManyOptions<Entity>): Promise<number> {
return this.manager.count(this.metadata.target, options)
}
/**
* Counts entities that match given conditions.
* Useful for pagination.
*/
countBy(
where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[],
): Promise<number> {
return this.manager.countBy(this.metadata.target, where)
}
/**
* Finds entities that match given find options.
*/
async find(options?: FindManyOptions<Entity>): Promise<Entity[]> {
return this.manager.find(this.metadata.target, options)
}
/**
* Finds entities that match given find options.
*/
async findBy(
where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[],
): Promise<Entity[]> {
return this.manager.findBy(this.metadata.target, where)
}
/**
* Finds entities that match given find options.
* Also counts all entities that match given conditions,
* but ignores pagination settings (from and take options).
*/
findAndCount(
options?: FindManyOptions<Entity>,
): Promise<[Entity[], number]> {
return this.manager.findAndCount(this.metadata.target, options)
}
/**
* Finds entities that match given WHERE conditions.
* Also counts all entities that match given conditions,
* but ignores pagination settings (from and take options).
*/
findAndCountBy(
where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[],
): Promise<[Entity[], number]> {
return this.manager.findAndCountBy(this.metadata.target, where)
}
/**
* Finds entities with ids.
* Optionally find options or conditions can be applied.
*
* @deprecated use `findBy` method instead in conjunction with `In` operator, for example:
*
* .findBy({
* id: In([1, 2, 3])
* })
*/
async findByIds(ids: any[]): Promise<Entity[]> {
return this.manager.findByIds(this.metadata.target, ids)
}
/**
* Finds first entity by a given find options.
* If entity was not found in the database - returns null.
*/
async findOne(options: FindOneOptions<Entity>): Promise<Entity | null> {
return this.manager.findOne(this.metadata.target, options)
}
/**
* Finds first entity that matches given where condition.
* If entity was not found in the database - returns null.
*/
async findOneBy(
where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[],
): Promise<Entity | null> {
return this.manager.findOneBy(this.metadata.target, where)
}
/**
* Finds first entity that matches given id.
* If entity was not found in the database - returns null.
*
* @deprecated use `findOneBy` method instead in conjunction with `In` operator, for example:
*
* .findOneBy({
* id: 1 // where "id" is your primary column name
* })
*/
async findOneById(
id: number | string | Date | ObjectID,
): Promise<Entity | null> {
return this.manager.findOneById(this.metadata.target, id)
}
/**
* Finds first entity by a given find options.
* If entity was not found in the database - rejects with error.
*/
async findOneOrFail(options: FindOneOptions<Entity>): Promise<Entity> {
return this.manager.findOneOrFail(this.metadata.target, options)
}
/**
* Finds first entity that matches given where condition.
* If entity was not found in the database - rejects with error.
*/
async findOneByOrFail(
where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[],
): Promise<Entity> {
return this.manager.findOneByOrFail(this.metadata.target, where)
}
/**
* Executes a raw SQL query and returns a raw database results.
* Raw query execution is supported only by relational databases (MongoDB is not supported).
*/
query(query: string, parameters?: any[]): Promise<any> {
return this.manager.query(query, parameters)
}
/**
* Clears all the data from the given table/collection (truncates/drops it).
*
* Note: this method uses TRUNCATE and may not work as you expect in transactions on some platforms.
* @see https://stackoverflow.com/a/5972738/925151
*/
clear(): Promise<void> {
return this.manager.clear(this.metadata.target)
}
/**
* Increments some column by provided value of the entities matched given conditions.
*/
increment(
conditions: FindOptionsWhere<Entity>,
propertyPath: string,
value: number | string,
): Promise<UpdateResult> {
return this.manager.increment(
this.metadata.target,
conditions,
propertyPath,
value,
)
}
/**
* Decrements some column by provided value of the entities matched given conditions.
*/
decrement(
conditions: FindOptionsWhere<Entity>,
propertyPath: string,
value: number | string,
): Promise<UpdateResult> {
return this.manager.decrement(
this.metadata.target,
conditions,
propertyPath,
value,
)
}
/**
* Extends repository with provided functions.
*/
extend<CustomRepository>(
custom: CustomRepository &
ThisType<Repository<Entity> & CustomRepository>,
): Repository<Entity> & CustomRepository {
// return {
// ...this,
// ...custom
// };
const thisRepo = this.constructor as new (...args: any[]) => typeof this
const { target, manager, queryRunner } = this
const cls = new (class extends thisRepo {})(
target,
manager,
queryRunner,
)
Object.assign(cls, custom)
return cls as any
}
}