-
-
Notifications
You must be signed in to change notification settings - Fork 6.2k
/
BaseEntity.ts
548 lines (498 loc) · 17.6 KB
/
BaseEntity.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
import { Repository } from "./Repository"
import { FindOptionsWhere } from "../find-options/FindOptionsWhere"
import { DeepPartial } from "../common/DeepPartial"
import { SaveOptions } from "./SaveOptions"
import { FindOneOptions } from "../find-options/FindOneOptions"
import { RemoveOptions } from "./RemoveOptions"
import { FindManyOptions } from "../find-options/FindManyOptions"
import { DataSource } from "../data-source"
import { SelectQueryBuilder } from "../query-builder/SelectQueryBuilder"
import { InsertResult } from "../query-builder/result/InsertResult"
import { UpdateResult } from "../query-builder/result/UpdateResult"
import { DeleteResult } from "../query-builder/result/DeleteResult"
import { ObjectID } from "../driver/mongodb/typings"
import { ObjectUtils } from "../util/ObjectUtils"
import { QueryDeepPartialEntity } from "../query-builder/QueryPartialEntity"
import { UpsertOptions } from "./UpsertOptions"
import { EntityTarget } from "../common/EntityTarget"
/**
* Base abstract entity for all entities, used in ActiveRecord patterns.
*/
export class BaseEntity {
// -------------------------------------------------------------------------
// Private Static Properties
// -------------------------------------------------------------------------
/**
* DataSource used in all static methods of the BaseEntity.
*/
private static dataSource: DataSource | null
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
/**
* Checks if entity has an id.
* If entity composite compose ids, it will check them all.
*/
hasId(): boolean {
const baseEntity = this.constructor as typeof BaseEntity
return baseEntity.getRepository().hasId(this)
}
/**
* Saves current entity in the database.
* If entity does not exist in the database then inserts, otherwise updates.
*/
save(options?: SaveOptions): Promise<this> {
const baseEntity = this.constructor as typeof BaseEntity
return baseEntity.getRepository().save(this, options)
}
/**
* Removes current entity from the database.
*/
remove(options?: RemoveOptions): Promise<this> {
const baseEntity = this.constructor as typeof BaseEntity
return baseEntity.getRepository().remove(this, options) as Promise<this>
}
/**
* Records the delete date of current entity.
*/
softRemove(options?: SaveOptions): Promise<this> {
const baseEntity = this.constructor as typeof BaseEntity
return baseEntity.getRepository().softRemove(this, options)
}
/**
* Recovers a given entity in the database.
*/
recover(options?: SaveOptions): Promise<this> {
const baseEntity = this.constructor as typeof BaseEntity
return baseEntity.getRepository().recover(this, options)
}
/**
* Reloads entity data from the database.
*/
async reload(): Promise<void> {
const baseEntity = this.constructor as typeof BaseEntity
const id = baseEntity.getRepository().metadata.getEntityIdMap(this)
if (!id) {
throw new Error(
`Entity doesn't have id-s set, cannot reload entity`,
)
}
const reloadedEntity: BaseEntity = await baseEntity
.getRepository()
.findOneByOrFail(id)
ObjectUtils.assign(this, reloadedEntity)
}
// -------------------------------------------------------------------------
// Public Static Methods
// -------------------------------------------------------------------------
/**
* Sets DataSource to be used by entity.
*/
static useDataSource(dataSource: DataSource | null) {
this.dataSource = dataSource
}
/**
* Gets current entity's Repository.
*/
static getRepository<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
): Repository<T> {
const dataSource = (this as typeof BaseEntity).dataSource
if (!dataSource)
throw new Error(`DataSource is not set for this entity.`)
return dataSource.getRepository<T>(this)
}
/**
* Returns object that is managed by this repository.
* If this repository manages entity from schema,
* then it returns a name of that schema instead.
*/
static get target(): EntityTarget<any> {
return this.getRepository().target
}
/**
* Checks entity has an id.
* If entity composite compose ids, it will check them all.
*/
static hasId(entity: BaseEntity): boolean {
return this.getRepository().hasId(entity)
}
/**
* Gets entity mixed id.
*/
static getId<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entity: T,
): any {
return this.getRepository<T>().getId(entity)
}
/**
* Creates a new query builder that can be used to build a SQL query.
*/
static createQueryBuilder<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
alias?: string,
): SelectQueryBuilder<T> {
return this.getRepository<T>().createQueryBuilder(alias)
}
/**
* Creates a new entity instance.
*/
static create<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
): T
/**
* Creates a new entities and copies all entity properties from given objects into their new entities.
* Note that it copies only properties that present in entity schema.
*/
static create<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entityLikeArray: DeepPartial<T>[],
): T[]
/**
* Creates a new entity instance and copies all entity properties from this object into a new entity.
* Note that it copies only properties that present in entity schema.
*/
static create<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entityLike: DeepPartial<T>,
): T
/**
* Creates a new entity instance and copies all entity properties from this object into a new entity.
* Note that it copies only properties that present in entity schema.
*/
static create<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entityOrEntities?: any,
) {
return this.getRepository<T>().create(entityOrEntities)
}
/**
* Merges multiple entities (or entity-like objects) into a given entity.
*/
static merge<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
mergeIntoEntity: T,
...entityLikes: DeepPartial<T>[]
): T {
return this.getRepository<T>().merge(
mergeIntoEntity,
...entityLikes,
) as T
}
/**
* 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.
*/
static preload<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entityLike: DeepPartial<T>,
): Promise<T | undefined> {
const thisRepository = this.getRepository() as Repository<T>
return thisRepository.preload(entityLike)
}
/**
* Saves all given entities in the database.
* If entities do not exist in the database then inserts, otherwise updates.
*/
static save<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entities: DeepPartial<T>[],
options?: SaveOptions,
): Promise<T[]>
/**
* Saves a given entity in the database.
* If entity does not exist in the database then inserts, otherwise updates.
*/
static save<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entity: DeepPartial<T>,
options?: SaveOptions,
): Promise<T>
/**
* Saves one or many given entities.
*/
static save<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entityOrEntities: DeepPartial<T> | DeepPartial<T>[],
options?: SaveOptions,
) {
return this.getRepository<T>().save(entityOrEntities as any, options)
}
/**
* Removes a given entities from the database.
*/
static remove<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entities: T[],
options?: RemoveOptions,
): Promise<T[]>
/**
* Removes a given entity from the database.
*/
static remove<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entity: T,
options?: RemoveOptions,
): Promise<T>
/**
* Removes one or many given entities.
*/
static remove<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entityOrEntities: T | T[],
options?: RemoveOptions,
) {
return this.getRepository<T>().remove(entityOrEntities as any, options)
}
/**
* Records the delete date of all given entities.
*/
static softRemove<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entities: T[],
options?: SaveOptions,
): Promise<T[]>
/**
* Records the delete date of a given entity.
*/
static softRemove<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entity: T,
options?: SaveOptions,
): Promise<T>
/**
* Records the delete date of one or many given entities.
*/
static softRemove<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entityOrEntities: T | T[],
options?: SaveOptions,
) {
return this.getRepository<T>().softRemove(
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.
*/
static insert<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entity: QueryDeepPartialEntity<T> | QueryDeepPartialEntity<T>[],
): Promise<InsertResult> {
return this.getRepository<T>().insert(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.
*/
static update<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
criteria:
| string
| string[]
| number
| number[]
| Date
| Date[]
| ObjectID
| ObjectID[]
| FindOptionsWhere<T>,
partialEntity: QueryDeepPartialEntity<T>,
): Promise<UpdateResult> {
return this.getRepository<T>().update(criteria, 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.
*/
static upsert<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
entityOrEntities:
| QueryDeepPartialEntity<T>
| QueryDeepPartialEntity<T>[],
conflictPathsOrOptions: string[] | UpsertOptions<T>,
): Promise<InsertResult> {
return this.getRepository<T>().upsert(
entityOrEntities,
conflictPathsOrOptions,
)
}
/**
* Deletes entities by a given criteria.
* Unlike remove 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.
*/
static delete<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
criteria:
| string
| string[]
| number
| number[]
| Date
| Date[]
| ObjectID
| ObjectID[]
| FindOptionsWhere<T>,
): Promise<DeleteResult> {
return this.getRepository<T>().delete(criteria)
}
/**
* Counts entities that match given options.
*/
static count<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
options?: FindManyOptions<T>,
): Promise<number> {
return this.getRepository<T>().count(options)
}
/**
* Counts entities that match given WHERE conditions.
*/
static countBy<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
where: FindOptionsWhere<T>,
): Promise<number> {
return this.getRepository<T>().countBy(where)
}
/**
* Finds entities that match given options.
*/
static find<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
options?: FindManyOptions<T>,
): Promise<T[]> {
return this.getRepository<T>().find(options)
}
/**
* Finds entities that match given WHERE conditions.
*/
static findBy<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
where: FindOptionsWhere<T>,
): Promise<T[]> {
return this.getRepository<T>().findBy(where)
}
/**
* Finds entities that match given find options.
* Also counts all entities that match given conditions,
* but ignores pagination settings (from and take options).
*/
static findAndCount<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
options?: FindManyOptions<T>,
): Promise<[T[], number]> {
return this.getRepository<T>().findAndCount(options)
}
/**
* Finds entities that match given WHERE conditions.
* Also counts all entities that match given conditions,
* but ignores pagination settings (from and take options).
*/
static findAndCountBy<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
where: FindOptionsWhere<T>,
): Promise<[T[], number]> {
return this.getRepository<T>().findAndCountBy(where)
}
/**
* Finds entities by ids.
* Optionally find options can be applied.
*
* @deprecated use `findBy` method instead in conjunction with `In` operator, for example:
*
* .findBy({
* id: In([1, 2, 3])
* })
*/
static findByIds<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
ids: any[],
): Promise<T[]> {
return this.getRepository<T>().findByIds(ids)
}
/**
* Finds first entity that matches given conditions.
*/
static findOne<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
options: FindOneOptions<T>,
): Promise<T | null> {
return this.getRepository<T>().findOne(options)
}
/**
* Finds first entity that matches given conditions.
*/
static findOneBy<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
where: FindOptionsWhere<T>,
): Promise<T | null> {
return this.getRepository<T>().findOneBy(where)
}
/**
* Finds first entity that matches given options.
*
* @deprecated use `findOneBy` method instead in conjunction with `In` operator, for example:
*
* .findOneBy({
* id: 1 // where "id" is your primary column name
* })
*/
static findOneById<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
id: string | number | Date | ObjectID,
): Promise<T | null> {
return this.getRepository<T>().findOneById(id)
}
/**
* Finds first entity that matches given conditions.
*/
static findOneOrFail<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
options: FindOneOptions<T>,
): Promise<T> {
return this.getRepository<T>().findOneOrFail(options)
}
/**
* Finds first entity that matches given conditions.
*/
static findOneByOrFail<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
where: FindOptionsWhere<T>,
): Promise<T> {
return this.getRepository<T>().findOneByOrFail(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).
*/
static query<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
query: string,
parameters?: any[],
): Promise<any> {
return this.getRepository<T>().query(query, parameters)
}
/**
* Clears all the data from the given table/collection (truncates/drops it).
*/
static clear<T extends BaseEntity>(
this: { new (): T } & typeof BaseEntity,
): Promise<void> {
return this.getRepository<T>().clear()
}
}