-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
legacy-juggler-bridge.ts
613 lines (554 loc) · 18.4 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
// Copyright IBM Corp. 2018,2019. 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 * as assert from 'assert';
import * as debugFactory from 'debug';
import * as legacy from 'loopback-datasource-juggler';
import {
AnyObject,
Command,
ConnectorCapabilities,
Count,
DataObject,
NamedParameters,
Options,
PositionalParameters,
} from '../common-types';
import {EntityNotFoundError} from '../errors';
import {Entity, Model, PropertyType} from '../model';
import {Filter, Inclusion, Where} from '../query';
import {
BelongsToAccessor,
BelongsToDefinition,
createBelongsToAccessor,
createHasManyRepositoryFactory,
createHasOneRepositoryFactory,
HasManyDefinition,
HasManyRepositoryFactory,
HasOneDefinition,
HasOneRepositoryFactory,
InclusionResolver,
RelationMetadata,
} from '../relations';
import {isTypeResolver, resolveType} from '../type-resolver';
import {EntityCrudRepository, WithCapabilities} from './repository';
const debug = debugFactory('loopback:repository:legacy-juggler-bridge');
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;
}
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>, WithCapabilities {
capabilities: ConnectorCapabilities;
modelClass: juggler.PersistedModelClass;
public inclusionResolvers: Map<string, InclusionResolver>;
/**
* Constructor of DefaultCrudRepository
* @param entityClass - Legacy entity class
* @param dataSource - Legacy 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,
) {
this.capabilities = {
// TODO(bajtos) add test coverage
inqLimit: dataSource.settings && dataSource.settings.inqLimit,
};
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.definePersistedModel(entityClass);
this.inclusionResolvers = new Map<string, InclusionResolver>();
}
// Create an internal legacy Model attached to the datasource
private definePersistedModel(
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;
}
// 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.definePersistedModel(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,
);
}
/**
* TODO - add docs
*/
protected registerInclusion(
relationName: string,
resolver: InclusionResolver,
) {
this.inclusionResolvers.set(relationName, resolver);
}
protected getRelationDefinition(relationName: string): RelationMetadata {
const relations = this.entityClass.definition.relations;
const meta = relations[relationName];
// FIXME(bajtos) Throw a helpful error when the relationName was not found
return meta;
}
/**
* @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> {
const model = await ensurePromise(
this.modelClass.create(
this.fromEntity(entity, {relations: 'throw'}),
options,
),
);
return this.toEntity(model);
}
async createAll(entities: DataObject<T>[], options?: Options): Promise<T[]> {
const models = await ensurePromise(
this.modelClass.create(
entities.map(e => this.fromEntity(e, {relations: 'throw'})),
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 models = await ensurePromise(
this.modelClass.find(this.normalizeFilter(filter), options),
);
const entities = this.toEntities(models);
return this.includeRelatedModels(entities, filter, 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 resolved = await this.includeRelatedModels([entity], filter, options);
return resolved[0];
}
async findById(
id: ID,
filter?: Filter<T>,
options?: Options,
): Promise<T & Relations> {
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], filter, options);
return resolved[0];
}
update(entity: T, options?: Options): Promise<void> {
return this.updateById(entity.getId(), entity, options);
}
delete(entity: T, options?: Options): Promise<void> {
return this.deleteById(entity.getId(), options);
}
async updateAll(
data: DataObject<T>,
where?: Where<T>,
options?: Options,
): Promise<Count> {
where = where || {};
const result = await ensurePromise(
this.modelClass.updateAll(where, this.fromEntity(data), options),
);
return {count: result.count};
}
async updateById(
id: ID,
data: DataObject<T>,
options?: Options,
): Promise<void> {
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 = this.fromEntity(data);
debug(
'%s replaceById',
this.modelClass.modelName,
typeof id,
id,
payload,
'options',
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));
}
// TODO(bajtos) add test coverage for all methods calling this helper
// and also test both variants (R.toJSON() and DataObject<R>)
protected fromEntity<R extends T>(
entity: R | DataObject<R>,
options: {relations?: true | false | 'throw'} = {},
): 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: AnyObject = new this.entityClass(entity);
if (options.relations === true) return data;
const def = this.entityClass.definition;
for (const r in def.relations) {
const relName = def.relations[r].name;
if (relName in data) {
if (options.relations === 'throw') {
throw new Error(
`Navigational properties are not allowed in model data (model "${this.entityClass.modelName}" property "${relName}")`,
);
}
delete data[relName];
}
}
return data;
}
protected normalizeFilter(filter?: Filter<T>): legacy.Filter | undefined {
if (!filter) return undefined;
return {...filter, include: undefined} as legacy.Filter;
}
// TODO(bajtos) Extract a public helper that other repositories can use too
protected async includeRelatedModels(
entities: T[],
filter?: Filter<T>,
options?: Options,
): Promise<(T & Relations)[]> {
const result = entities as (T & Relations)[];
const include = filter && filter.include;
if (!include) return result;
const invalidInclusions = include.filter(i => !this.isInclusionAllowed(i));
if (invalidInclusions.length) {
const msg =
'Invalid "filter.include" entries: ' +
invalidInclusions.map(i => JSON.stringify(i)).join('; ');
const err = new Error(msg);
Object.assign(err, {
code: 'INVALID_INCLUSION_FILTER',
});
throw err;
}
const resolveTasks = include.map(async i => {
const relationName = i.relation!;
const resolver = this.inclusionResolvers.get(relationName)!;
const targets = await resolver(entities, i, options);
for (const ix in result) {
const src = result[ix];
(src as AnyObject)[relationName] = targets[ix];
}
});
await Promise.all(resolveTasks);
return result;
}
private isInclusionAllowed(inclusion: Inclusion): boolean {
const relationName = inclusion.relation;
if (!relationName) {
debug('isInclusionAllowed for %j? No: missing relation name', inclusion);
return false;
}
const allowed = this.inclusionResolvers.has(relationName);
debug('isInclusionAllowed for %j (relation %s)? %s', inclusion, allowed);
return allowed;
}
}