/
legacy-juggler-bridge.ts
639 lines (588 loc) · 19.5 KB
/
legacy-juggler-bridge.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
// Copyright IBM Corp. 2018,2020. All Rights Reserved.
// Node module: @loopback/repository
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {Getter} from '@loopback/context';
import assert from 'assert';
import legacy from 'loopback-datasource-juggler';
import {
AnyObject,
Command,
Count,
DataObject,
DeepPartial,
NamedParameters,
Options,
PositionalParameters,
} from '../common-types';
import {EntityNotFoundError} from '../errors';
import {
Entity,
Model,
PropertyType,
rejectNavigationalPropertiesInData,
} from '../model';
import {Filter, FilterExcludingWhere, Inclusion, Where} from '../query';
import {
BelongsToAccessor,
BelongsToDefinition,
createBelongsToAccessor,
createHasManyRepositoryFactory,
createHasOneRepositoryFactory,
HasManyDefinition,
HasManyRepositoryFactory,
HasOneDefinition,
HasOneRepositoryFactory,
includeRelatedModels,
InclusionResolver,
} from '../relations';
import {IsolationLevel, Transaction} from '../transaction';
import {isTypeResolver, resolveType} from '../type-resolver';
import {
EntityCrudRepository,
TransactionalEntityRepository,
} from './repository';
export namespace juggler {
/* eslint-disable @typescript-eslint/no-unused-vars */
export import DataSource = legacy.DataSource;
export import ModelBase = legacy.ModelBase;
export import ModelBaseClass = legacy.ModelBaseClass;
export import PersistedModel = legacy.PersistedModel;
export import KeyValueModel = legacy.KeyValueModel;
export import PersistedModelClass = legacy.PersistedModelClass;
// eslint-disable-next-line no-shadow
export import Transaction = legacy.Transaction;
// eslint-disable-next-line no-shadow
export import IsolationLevel = legacy.IsolationLevel;
}
function isModelClass(
propertyType: PropertyType | undefined,
): propertyType is typeof Model {
return (
!isTypeResolver(propertyType) &&
typeof propertyType === 'function' &&
typeof (propertyType as typeof Model).definition === 'object' &&
propertyType.toString().startsWith('class ')
);
}
/**
* This is a bridge to the legacy DAO class. The function mixes DAO methods
* into a model class and attach it to a given data source
* @param modelClass - Model class
* @param ds - Data source
* @returns {} The new model class with DAO (CRUD) operations
*/
export function bindModel<T extends juggler.ModelBaseClass>(
modelClass: T,
ds: juggler.DataSource,
): T {
const BoundModelClass = class extends modelClass {};
BoundModelClass.attachTo(ds);
return BoundModelClass;
}
/**
* Ensure the value is a promise
* @param p - Promise or void
*/
export function ensurePromise<T>(p: legacy.PromiseOrVoid<T>): Promise<T> {
if (p && p instanceof Promise) {
return p;
} else {
return Promise.reject(new Error('The value should be a Promise: ' + p));
}
}
/**
* Default implementation of CRUD repository using legacy juggler model
* and data source
*/
export class DefaultCrudRepository<
T extends Entity,
ID,
Relations extends object = {}
> implements EntityCrudRepository<T, ID, Relations> {
modelClass: juggler.PersistedModelClass;
public readonly inclusionResolvers: Map<
string,
InclusionResolver<T, Entity>
> = new Map();
/**
* Constructor of DefaultCrudRepository
* @param entityClass - LoopBack 4 entity class
* @param dataSource - Legacy juggler data source
*/
constructor(
// entityClass should have type "typeof T", but that's not supported by TSC
public entityClass: typeof Entity & {prototype: T},
public dataSource: juggler.DataSource,
) {
const definition = entityClass.definition;
assert(
!!definition,
`Entity ${entityClass.name} must have valid model definition.`,
);
assert(
definition.idProperties().length > 0,
`Entity ${entityClass.name} must have at least one id/pk property.`,
);
this.modelClass = this.ensurePersistedModel(entityClass);
}
// Create an internal legacy Model attached to the datasource
private ensurePersistedModel(
entityClass: typeof Model,
): typeof juggler.PersistedModel {
const definition = entityClass.definition;
assert(
!!definition,
`Entity ${entityClass.name} must have valid model definition.`,
);
const dataSource = this.dataSource;
const model = dataSource.getModel(definition.name);
if (model) {
// The backing persisted model has been already defined.
return model as typeof juggler.PersistedModel;
}
return this.definePersistedModel(entityClass);
}
/**
* Creates a legacy persisted model class, attaches it to the datasource and
* returns it. This method can be overriden in sub-classes to acess methods
* and properties in the generated model class.
* @param entityClass - LB4 Entity constructor
*/
protected definePersistedModel(
entityClass: typeof Model,
): typeof juggler.PersistedModel {
const dataSource = this.dataSource;
const definition = entityClass.definition;
// To handle circular reference back to the same model,
// we create a placeholder model that will be replaced by real one later
dataSource.getModel(definition.name, true /* forceCreate */);
// We need to convert property definitions from PropertyDefinition
// to plain data object because of a juggler limitation
const properties: {[name: string]: object} = {};
// We need to convert PropertyDefinition into the definition that
// the juggler understands
Object.entries(definition.properties).forEach(([key, value]) => {
// always clone value so that we do not modify the original model definition
// ensures that model definitions can be reused with multiple datasources
if (value.type === 'array' || value.type === Array) {
value = Object.assign({}, value, {
type: [value.itemType && this.resolvePropertyType(value.itemType)],
});
delete value.itemType;
} else {
value = Object.assign({}, value, {
type: this.resolvePropertyType(value.type),
});
}
properties[key] = Object.assign({}, value);
});
const modelClass = dataSource.createModel<juggler.PersistedModelClass>(
definition.name,
properties,
Object.assign(
// settings that users can override
{strict: true},
// user-defined settings
definition.settings,
// settings enforced by the framework
{strictDelete: false},
),
);
modelClass.attachTo(dataSource);
return modelClass;
}
private resolvePropertyType(type: PropertyType): PropertyType {
const resolved = resolveType(type);
return isModelClass(resolved)
? this.ensurePersistedModel(resolved)
: resolved;
}
/**
* @deprecated
* Function to create a constrained relation repository factory
*
* Use `this.createHasManyRepositoryFactoryFor()` instead
*
* @param relationName - Name of the relation defined on the source model
* @param targetRepo - Target repository instance
*/
protected _createHasManyRepositoryFactoryFor<
Target extends Entity,
TargetID,
ForeignKeyType
>(
relationName: string,
targetRepoGetter: Getter<EntityCrudRepository<Target, TargetID>>,
): HasManyRepositoryFactory<Target, ForeignKeyType> {
return this.createHasManyRepositoryFactoryFor(
relationName,
targetRepoGetter,
);
}
/**
* Function to create a constrained relation repository factory
*
* @example
* ```ts
* class CustomerRepository extends DefaultCrudRepository<
* Customer,
* typeof Customer.prototype.id,
* CustomerRelations
* > {
* public readonly orders: HasManyRepositoryFactory<Order, typeof Customer.prototype.id>;
*
* constructor(
* protected db: juggler.DataSource,
* orderRepository: EntityCrudRepository<Order, typeof Order.prototype.id>,
* ) {
* super(Customer, db);
* this.orders = this._createHasManyRepositoryFactoryFor(
* 'orders',
* orderRepository,
* );
* }
* }
* ```
*
* @param relationName - Name of the relation defined on the source model
* @param targetRepo - Target repository instance
*/
protected createHasManyRepositoryFactoryFor<
Target extends Entity,
TargetID,
ForeignKeyType
>(
relationName: string,
targetRepoGetter: Getter<EntityCrudRepository<Target, TargetID>>,
): HasManyRepositoryFactory<Target, ForeignKeyType> {
const meta = this.entityClass.definition.relations[relationName];
return createHasManyRepositoryFactory<Target, TargetID, ForeignKeyType>(
meta as HasManyDefinition,
targetRepoGetter,
);
}
/**
* @deprecated
* Function to create a belongs to accessor
*
* Use `this.createBelongsToAccessorFor()` instead
*
* @param relationName - Name of the relation defined on the source model
* @param targetRepo - Target repository instance
*/
protected _createBelongsToAccessorFor<Target extends Entity, TargetId>(
relationName: string,
targetRepoGetter: Getter<EntityCrudRepository<Target, TargetId>>,
): BelongsToAccessor<Target, ID> {
return this.createBelongsToAccessorFor(relationName, targetRepoGetter);
}
/**
* Function to create a belongs to accessor
*
* @param relationName - Name of the relation defined on the source model
* @param targetRepo - Target repository instance
*/
protected createBelongsToAccessorFor<Target extends Entity, TargetId>(
relationName: string,
targetRepoGetter: Getter<EntityCrudRepository<Target, TargetId>>,
): BelongsToAccessor<Target, ID> {
const meta = this.entityClass.definition.relations[relationName];
return createBelongsToAccessor<Target, TargetId, T, ID>(
meta as BelongsToDefinition,
targetRepoGetter,
this,
);
}
/**
* @deprecated
* Function to create a constrained hasOne relation repository factory
*
* @param relationName - Name of the relation defined on the source model
* @param targetRepo - Target repository instance
*/
protected _createHasOneRepositoryFactoryFor<
Target extends Entity,
TargetID,
ForeignKeyType
>(
relationName: string,
targetRepoGetter: Getter<EntityCrudRepository<Target, TargetID>>,
): HasOneRepositoryFactory<Target, ForeignKeyType> {
return this.createHasOneRepositoryFactoryFor(
relationName,
targetRepoGetter,
);
}
/**
* Function to create a constrained hasOne relation repository factory
*
* @param relationName - Name of the relation defined on the source model
* @param targetRepo - Target repository instance
*/
protected createHasOneRepositoryFactoryFor<
Target extends Entity,
TargetID,
ForeignKeyType
>(
relationName: string,
targetRepoGetter: Getter<EntityCrudRepository<Target, TargetID>>,
): HasOneRepositoryFactory<Target, ForeignKeyType> {
const meta = this.entityClass.definition.relations[relationName];
return createHasOneRepositoryFactory<Target, TargetID, ForeignKeyType>(
meta as HasOneDefinition,
targetRepoGetter,
);
}
async create(entity: DataObject<T>, options?: Options): Promise<T> {
// perform persist hook
const data = await this.entityToData(entity, options);
const model = await ensurePromise(this.modelClass.create(data, options));
return this.toEntity(model);
}
async createAll(entities: DataObject<T>[], options?: Options): Promise<T[]> {
// perform persist hook
const data = await Promise.all(
entities.map(e => this.entityToData(e, options)),
);
const models = await ensurePromise(this.modelClass.create(data, options));
return this.toEntities(models);
}
async save(entity: T, options?: Options): Promise<T> {
const id = this.entityClass.getIdOf(entity);
if (id == null) {
return this.create(entity, options);
} else {
await this.replaceById(id, entity, options);
return new this.entityClass(entity.toObject()) as T;
}
}
async find(
filter?: Filter<T>,
options?: Options,
): Promise<(T & Relations)[]> {
const include = filter?.include;
const models = await ensurePromise(
this.modelClass.find(this.normalizeFilter(filter), options),
);
const entities = this.toEntities(models);
return this.includeRelatedModels(entities, include, options);
}
async findOne(
filter?: Filter<T>,
options?: Options,
): Promise<(T & Relations) | null> {
const model = await ensurePromise(
this.modelClass.findOne(this.normalizeFilter(filter), options),
);
if (!model) return null;
const entity = this.toEntity(model);
const include = filter?.include;
const resolved = await this.includeRelatedModels(
[entity],
include,
options,
);
return resolved[0];
}
async findById(
id: ID,
filter?: FilterExcludingWhere<T>,
options?: Options,
): Promise<T & Relations> {
const include = filter?.include;
const model = await ensurePromise(
this.modelClass.findById(id, this.normalizeFilter(filter), options),
);
if (!model) {
throw new EntityNotFoundError(this.entityClass, id);
}
const entity = this.toEntity(model);
const resolved = await this.includeRelatedModels(
[entity],
include,
options,
);
return resolved[0];
}
update(entity: T, options?: Options): Promise<void> {
return this.updateById(entity.getId(), entity, options);
}
async delete(entity: T, options?: Options): Promise<void> {
// perform persist hook
await this.entityToData(entity, options);
return this.deleteById(entity.getId(), options);
}
async updateAll(
data: DataObject<T>,
where?: Where<T>,
options?: Options,
): Promise<Count> {
where = where ?? {};
const persistedData = await this.entityToData(data, options);
const result = await ensurePromise(
this.modelClass.updateAll(where, persistedData, options),
);
return {count: result.count};
}
async updateById(
id: ID,
data: DataObject<T>,
options?: Options,
): Promise<void> {
if (id === undefined) {
throw new Error('Invalid Argument: id cannot be undefined');
}
const idProp = this.modelClass.definition.idName();
const where = {} as Where<T>;
(where as AnyObject)[idProp] = id;
const result = await this.updateAll(data, where, options);
if (result.count === 0) {
throw new EntityNotFoundError(this.entityClass, id);
}
}
async replaceById(
id: ID,
data: DataObject<T>,
options?: Options,
): Promise<void> {
try {
const payload = await this.entityToData(data, options);
await ensurePromise(this.modelClass.replaceById(id, payload, options));
} catch (err) {
if (err.statusCode === 404) {
throw new EntityNotFoundError(this.entityClass, id);
}
throw err;
}
}
async deleteAll(where?: Where<T>, options?: Options): Promise<Count> {
const result = await ensurePromise(
this.modelClass.deleteAll(where, options),
);
return {count: result.count};
}
async deleteById(id: ID, options?: Options): Promise<void> {
const result = await ensurePromise(this.modelClass.deleteById(id, options));
if (result.count === 0) {
throw new EntityNotFoundError(this.entityClass, id);
}
}
async count(where?: Where<T>, options?: Options): Promise<Count> {
const result = await ensurePromise(this.modelClass.count(where, options));
return {count: result};
}
exists(id: ID, options?: Options): Promise<boolean> {
return ensurePromise(this.modelClass.exists(id, options));
}
async execute(
command: Command,
parameters: NamedParameters | PositionalParameters,
options?: Options,
): Promise<AnyObject> {
return ensurePromise(this.dataSource.execute(command, parameters, options));
}
protected toEntity<R extends T>(model: juggler.PersistedModel): R {
return new this.entityClass(model.toObject()) as R;
}
protected toEntities<R extends T>(models: juggler.PersistedModel[]): R[] {
return models.map(m => this.toEntity<R>(m));
}
/**
* Register an inclusion resolver for the related model name.
*
* @param relationName - Name of the relation defined on the source model
* @param resolver - Resolver function for getting related model entities
*/
registerInclusionResolver(
relationName: string,
resolver: InclusionResolver<T, Entity>,
) {
this.inclusionResolvers.set(relationName, resolver);
}
/**
* Returns model instances that include related models of this repository
* that have a registered resolver.
*
* @param entities - An array of entity instances or data
* @param include -Inclusion filter
* @param options - Options for the operations
*/
protected async includeRelatedModels(
entities: T[],
include?: Inclusion[],
options?: Options,
): Promise<(T & Relations)[]> {
return includeRelatedModels<T, Relations>(this, entities, include, options);
}
/**
* This function works as a persist hook.
* It converts an entity from the CRUD operations' caller
* to a persistable data that can will be stored in the
* back-end database.
*
* User can extend `DefaultCrudRepository` then override this
* function to execute custom persist hook.
* @param entity The entity passed from CRUD operations' caller.
* @param options
*/
protected async entityToData<R extends T>(
entity: R | DataObject<R>,
options = {},
): Promise<legacy.ModelData<legacy.PersistedModel>> {
return this.ensurePersistable(entity, options);
}
/** Converts an entity object to a JSON object to check if it contains navigational property.
* Throws an error if `entity` contains navigational property.
*
* @param entity The entity passed from CRUD operations' caller.
* @param options
*/
protected ensurePersistable<R extends T>(
entity: R | DataObject<R>,
options = {},
): legacy.ModelData<legacy.PersistedModel> {
// FIXME(bajtos) Ideally, we should call toJSON() to convert R to data object
// Unfortunately that breaks replaceById for MongoDB connector, where we
// would call replaceId with id *argument* set to ObjectID value but
// id *property* set to string value.
/*
const data: AnyObject =
typeof entity.toJSON === 'function' ? entity.toJSON() : {...entity};
*/
const data: DeepPartial<R> = new this.entityClass(entity);
rejectNavigationalPropertiesInData(this.entityClass, data);
return data;
}
/**
* Removes juggler's "include" filter as it does not apply to LoopBack 4
* relations.
*
* @param filter - Query filter
*/
protected normalizeFilter(filter?: Filter<T>): legacy.Filter | undefined {
if (!filter) return undefined;
return {...filter, include: undefined} as legacy.Filter;
}
}
/**
* Default implementation of CRUD repository using legacy juggler model
* and data source with beginTransaction() method for connectors which
* support Transactions
*/
export class DefaultTransactionalRepository<
T extends Entity,
ID,
Relations extends object = {}
> extends DefaultCrudRepository<T, ID, Relations>
implements TransactionalEntityRepository<T, ID, Relations> {
async beginTransaction(
options?: IsolationLevel | Options,
): Promise<Transaction> {
const dsOptions: juggler.IsolationLevel | Options = options ?? {};
// juggler.Transaction still has the Promise/Callback variants of the
// Transaction methods
// so we need it cast it back
return (await this.dataSource.beginTransaction(dsOptions)) as Transaction;
}
}