-
-
Notifications
You must be signed in to change notification settings - Fork 496
/
EntityManager.ts
316 lines (247 loc) · 10.7 KB
/
EntityManager.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
import { Configuration, RequestContext, Utils } from './utils';
import { EntityAssigner, EntityFactory, EntityLoader, EntityRepository, EntityValidator, ReferenceType } from './entity';
import { UnitOfWork } from './unit-of-work';
import { FilterQuery, IDatabaseDriver } from './drivers';
import { EntityData, EntityName, IEntity, IEntityType, IPrimaryKey } from './decorators';
import { QueryBuilder, QueryOrder, SmartQueryHelper } from './query';
import { MetadataStorage } from './metadata';
import { Connection } from './connections';
export class EntityManager {
private readonly validator = new EntityValidator(this.config.get('strict'));
private readonly repositoryMap: Record<string, EntityRepository<IEntity>> = {};
private readonly entityLoader = new EntityLoader(this);
private readonly metadata = MetadataStorage.getMetadata();
private readonly unitOfWork = new UnitOfWork(this);
private readonly entityFactory = new EntityFactory(this.unitOfWork, this.driver, this.config);
constructor(readonly config: Configuration,
private readonly driver: IDatabaseDriver<Connection>) { }
getDriver<D extends IDatabaseDriver<Connection> = IDatabaseDriver<Connection>>(): D {
return this.driver as D;
}
getConnection<C extends Connection = Connection>(): C {
return this.driver.getConnection() as C;
}
getRepository<T extends IEntityType<T>>(entityName: EntityName<T>): EntityRepository<T> {
entityName = Utils.className(entityName);
if (!this.repositoryMap[entityName]) {
const meta = this.metadata[entityName];
const RepositoryClass = this.config.getRepositoryClass(meta.customRepository);
this.repositoryMap[entityName] = new RepositoryClass(this, entityName);
}
return this.repositoryMap[entityName] as EntityRepository<T>;
}
getValidator(): EntityValidator {
return this.validator;
}
createQueryBuilder(entityName: EntityName<IEntity>): QueryBuilder {
entityName = Utils.className(entityName);
return new QueryBuilder(entityName, this.metadata, this.getConnection(), this.driver.getPlatform());
}
async find<T extends IEntityType<T>>(entityName: EntityName<T>, where?: FilterQuery<T>, options?: FindOptions): Promise<T[]>;
async find<T extends IEntityType<T>>(entityName: EntityName<T>, where?: FilterQuery<T>, populate?: string[], orderBy?: Record<string, QueryOrder>, limit?: number, offset?: number): Promise<T[]>;
async find<T extends IEntityType<T>>(entityName: EntityName<T>, where = {} as FilterQuery<T>, populate?: string[] | FindOptions, orderBy?: Record<string, QueryOrder>, limit?: number, offset?: number): Promise<T[]> {
entityName = Utils.className(entityName);
where = SmartQueryHelper.processWhere(where);
this.validator.validateParams(where);
const options = Utils.isObject<FindOptions>(populate) ? populate : { populate, orderBy, limit, offset };
const results = await this.driver.find(entityName, where, options.populate || [], options.orderBy || {}, options.limit, options.offset);
if (results.length === 0) {
return [];
}
const ret: T[] = [];
for (const data of results) {
const entity = this.merge<T>(entityName, data);
ret.push(entity);
}
await this.entityLoader.populate(entityName, ret, options.populate || []);
return ret;
}
async findOne<T extends IEntityType<T>>(entityName: EntityName<T>, where: FilterQuery<T> | IPrimaryKey, populate: string[] = []): Promise<T | null> {
entityName = Utils.className(entityName);
if (!where || (typeof where === 'object' && Object.keys(where).length === 0)) {
throw new Error(`You cannot call 'EntityManager.findOne()' with empty 'where' parameter`);
}
let entity = this.getUnitOfWork().tryGetById<T>(entityName, where);
if (entity && entity.isInitialized()) {
await this.entityLoader.populate(entityName, [entity], populate);
return entity;
}
where = SmartQueryHelper.processWhere(where as FilterQuery<T>);
this.validator.validateParams(where);
const data = await this.driver.findOne(entityName, where, populate);
if (!data) {
return null;
}
entity = this.merge(entityName, data) as T;
await this.entityLoader.populate(entityName, [entity], populate);
return entity;
}
async beginTransaction(): Promise<void> {
await this.driver.beginTransaction();
}
async commit(): Promise<void> {
await this.driver.commit();
}
async rollback(): Promise<void> {
await this.driver.rollback();
}
async transactional(cb: (em: EntityManager) => Promise<any>): Promise<any> {
const em = this.fork();
await em.getDriver().transactional(async () => {
const ret = await cb(em);
await em.flush();
return ret;
});
}
async nativeInsert<T extends IEntityType<T>>(entityName: EntityName<T>, data: EntityData<T>): Promise<IPrimaryKey> {
entityName = Utils.className(entityName);
this.validator.validateParams(data, 'insert data');
const res = await this.driver.nativeInsert(entityName, data);
return res.insertId;
}
async nativeUpdate<T extends IEntityType<T>>(entityName: EntityName<T>, where: FilterQuery<T>, data: EntityData<T>): Promise<number> {
entityName = Utils.className(entityName);
where = SmartQueryHelper.processWhere(where as FilterQuery<T>);
this.validator.validateParams(data, 'update data');
this.validator.validateParams(where, 'update condition');
const res = await this.driver.nativeUpdate(entityName, where, data);
return res.affectedRows;
}
async nativeDelete<T extends IEntityType<T>>(entityName: EntityName<T>, where: FilterQuery<T> | string | any): Promise<number> {
entityName = Utils.className(entityName);
where = SmartQueryHelper.processWhere(where as FilterQuery<T>);
this.validator.validateParams(where, 'delete condition');
const res = await this.driver.nativeDelete(entityName, where);
return res.affectedRows;
}
/**
* Shortcut to driver's aggregate method. Available in MongoDriver only.
*/
async aggregate(entityName: EntityName<IEntity>, pipeline: any[]): Promise<any[]> {
entityName = Utils.className(entityName);
return this.driver.aggregate(entityName, pipeline);
}
merge<T extends IEntityType<T>>(entity: T): T;
merge<T extends IEntityType<T>>(entityName: EntityName<T>, data: EntityData<T>): T;
merge<T extends IEntityType<T>>(entityName: EntityName<T> | T, data?: EntityData<T>): T {
if (Utils.isEntity(entityName)) {
return this.merge(entityName.constructor.name, entityName as EntityData<T>);
}
entityName = Utils.className(entityName);
this.validator.validatePrimaryKey(data!, this.metadata[entityName]);
const entity = Utils.isEntity<T>(data) ? data : this.getEntityFactory().create<T>(entityName, data!, true);
// add to IM immediately - needed for self-references that can be part of `data` (and do not trigger cascade merge)
this.getUnitOfWork().merge(entity, [entity]);
EntityAssigner.assign(entity, data!, true);
this.getUnitOfWork().merge(entity); // add to IM again so we have correct payload saved to change set computation
return entity;
}
/**
* Creates new instance of given entity and populates it with given data
*/
create<T extends IEntityType<T>>(entityName: EntityName<T>, data: EntityData<T>): T {
return this.getEntityFactory().create(entityName, data, false);
}
/**
* Gets a reference to the entity identified by the given type and identifier without actually loading it, if the entity is not yet loaded
*/
getReference<T extends IEntityType<T>>(entityName: EntityName<T>, id: IPrimaryKey): T {
entityName = Utils.className(entityName);
if (this.getUnitOfWork().getById(entityName, id)) {
return this.getUnitOfWork().getById<T>(entityName, id);
}
const entity = this.getEntityFactory().createReference<T>(entityName, id);
this.getUnitOfWork().merge(entity);
return entity;
}
async count<T extends IEntityType<T>>(entityName: EntityName<T>, where: FilterQuery<T>): Promise<number> {
entityName = Utils.className(entityName);
where = SmartQueryHelper.processWhere(where as FilterQuery<T>);
this.validator.validateParams(where);
return this.driver.count(entityName, where);
}
async persist(entity: IEntity | IEntity[], flush = this.config.get('autoFlush')): Promise<void> {
if (flush) {
await this.persistAndFlush(entity);
} else {
this.persistLater(entity);
}
}
async persistAndFlush(entity: IEntity | IEntity[]): Promise<void> {
entity = Array.isArray(entity) ? entity : [entity];
for (const ent of entity) {
this.getUnitOfWork().persist(ent);
}
await this.flush();
}
persistLater(entity: IEntity | IEntity[]): void {
entity = Array.isArray(entity) ? entity : [entity];
for (const ent of entity) {
this.getUnitOfWork().persist(ent);
}
}
async remove<T extends IEntityType<T>>(entityName: EntityName<T>, where: T | any, flush = this.config.get('autoFlush')): Promise<number> {
entityName = Utils.className(entityName);
if (Utils.isEntity(where)) {
await this.removeEntity(where, flush);
return 1;
}
return this.nativeDelete(entityName, where);
}
async removeEntity(entity: IEntity, flush = this.config.get('autoFlush')): Promise<void> {
if (flush) {
await this.removeAndFlush(entity);
} else {
this.removeLater(entity);
}
}
async removeAndFlush(entity: IEntity): Promise<void> {
this.getUnitOfWork().remove(entity);
await this.flush();
}
removeLater(entity: IEntity): void {
this.getUnitOfWork().remove(entity);
}
/**
* flush changes to database
*/
async flush(): Promise<void> {
await this.getUnitOfWork().commit();
}
/**
* clear identity map, detaching all entities
*/
clear(): void {
this.getUnitOfWork().clear();
}
canPopulate(entityName: string | Function, property: string): boolean {
entityName = Utils.className(entityName);
const [p, ...parts] = property.split('.');
const props = this.metadata[entityName].properties;
const ret = p in props && props[p].reference !== ReferenceType.SCALAR;
if (!ret) {
return false;
}
if (parts.length > 0) {
return this.canPopulate(props[p].type, parts.join('.'));
}
return ret;
}
fork(): EntityManager {
return new EntityManager(this.config, this.driver);
}
getUnitOfWork(): UnitOfWork {
const em = RequestContext.getEntityManager() || this;
return em.unitOfWork;
}
getEntityFactory(): EntityFactory {
const em = RequestContext.getEntityManager() || this;
return em.entityFactory;
}
}
export interface FindOptions {
populate?: string[];
orderBy?: Record<string, QueryOrder>;
limit?: number;
offset?: number;
}