/
HasRelations.ts
595 lines (506 loc) · 19.7 KB
/
HasRelations.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
import ModelCollection from '../ModelCollection';
import type Model from '../Model';
import LogicException from '../../Exceptions/LogicException';
import CallsApi from './CallsApi';
import InvalidOffsetException from '../../Exceptions/InvalidOffsetException';
import type { Attributes } from './HasAttributes';
import Collection from '../../Support/Collection';
import InvalidArgumentException from '../../Exceptions/InvalidArgumentException';
import finish from '../../Support/string/finish';
import plural from '../../Support/string/plural';
import snake from '../../Support/string/snake';
import start from '../../Support/string/start';
import cloneDeep from 'lodash.clonedeep';
import type { MaybeArray } from '../../Support/type';
type Relation = 'belongsTo' | 'belongsToMany' | 'hasMany' | 'hasOne' | 'morphMany' | 'morphOne' | 'morphTo';
type MorphToCallback<
MT extends HasRelations,
T extends Model = Model
> = (self: MT, relatedData: Attributes<T>) => typeof Model;
export default class HasRelations extends CallsApi {
/**
* The loaded relations for the model.
* The keys do not include the relation prefixes.
*
* @protected
*/
protected relations: Record<string, (Model | ModelCollection<Model>)> = {};
/**
* The string all the relation methods expected to prefixed by.
*
* @protected
*
* @return {string}
*/
protected get relationMethodPrefix(): string {
return '$';
}
/**
* The key name of the parent of this model which was
* instantiated from a hasOne or hasMany relation.
* This is used to remove the where query when saving
* a new entity like `parent.$child().save({});`
*
* @protected
*/
protected hasOneOrManyParentKeyName: string | undefined;
/**
* Load relationship(s) from remote.
*
* @param {string|string[]} relations
* @param {boolean} forceReload - Whether the already loaded relations should also be reloaded.
*
* @return {Promise<this>}
*/
public async load(relations: MaybeArray<string>, forceReload = false): Promise<this> {
this.throwIfModelDoesntExistsWhenCalling('load');
if (!Array.isArray(relations)) {
relations = [relations];
}
relations = relations.filter(relation => forceReload || !this.relationLoaded(relation));
relations.forEach(relation => {
if (!this.relationDefined(relation)) {
throw new InvalidOffsetException('\'' + relation + '\' relationship is not defined.');
}
});
if (!relations.length) {
return this;
}
if (relations.length === 1) {
const relation = await
((this[start(relations[0]!, this.relationMethodPrefix)] as CallableFunction)() as Model)
.get();
this.addRelation(relations[0]!, relation);
return this;
}
const returnedRelations = (await this.with(relations).setModelEndpoint().get<this>()).getRelations();
Object.keys(returnedRelations).forEach(returnedRelation => {
this.addRelation(returnedRelation, returnedRelations[returnedRelation]!);
});
return this;
}
/**
* Determine if the given relation is loaded.
*
* @param {string} name
*/
public relationLoaded(name: string): boolean {
return this.loadedRelationKeys().includes(this.removeRelationPrefix(name));
}
/**
* Get an array of loaded relation names.
*
* @return {string[]}
*/
public loadedRelationKeys(): string[] {
return Object.keys(this.getRelations());
}
/**
* Get the specified relationship.
*
* @param {string} name
*
* @return {Model|ModelCollection}
*/
public getRelation<T extends Model>(name: string): ModelCollection<T> | T {
name = this.removeRelationPrefix(name);
if (!this.relationDefined(name)) {
throw new InvalidArgumentException('\'' + name + '\' relationship is not defined.');
}
if (!this.relations[name]) {
throw new LogicException(
'Trying to access the \'' + name + '\' relationship before it is loaded.'
);
}
return cloneDeep(this.relations[name]!) as ModelCollection<T> | T;
}
/**
* Assert whether the relation has been defined on this instance.
*
* @param {string} name
* @protected
*
* @return {boolean}
*/
protected relationDefined(name: string): boolean {
name = start(name, this.relationMethodPrefix);
if (this[name] instanceof Function) {
const value = (this[name] as CallableFunction)();
return value instanceof HasRelations && !!this.getRelationType(name);
}
return false;
}
/**
* Get the name of the relation type for the given relation.
*
* @param {string} name
*
* @protected
*
* @return {Relation}
*/
protected getRelationType(name: string): Relation {
name = start(name, this.relationMethodPrefix);
const model = (this[name] as CallableFunction)() as Model & { _relationType?: Relation };
if (!model._relationType) {
throw new LogicException('\'' + name + '\' relation is not using any of the expected relation types.');
}
return model._relationType;
}
/**
* Parse the given data into a related model class
* and add the relation to this instance.
*
* @param {string} name
* @param {Model|ModelCollection|object|object[]} value
*
* @return this
*/
public addRelation<T extends Model>(
name: string,
value: Collection<Attributes>
| Collection<T>
| MaybeArray<Attributes>
| MaybeArray<T>
| ModelCollection<T>
): this {
name = this.removeRelationPrefix(name);
if (!this.relationDefined(name)) {
throw new LogicException(
'Attempted to add an undefined relation: \'' + name + '\'.'
);
}
const relationType = this.getRelationType(name);
const isSingularRelationType = ['belongsTo', 'hasOne', 'morphOne', 'morphTo'].includes(relationType);
const isModelArray = Array.isArray(value) && value.every(entry => entry instanceof HasRelations);
/**
* Callback acting as user guard for collection of models.
* ModelCollection is a subclass of Collection.
*/
const isCollectionWithModels = (val: any): val is Collection<T> => Collection.isCollection(val)
&& val.every(entry => entry instanceof HasRelations);
if (value instanceof HasRelations || isCollectionWithModels(value) || isModelArray) {
if (isSingularRelationType && (isCollectionWithModels(value) || isModelArray)) {
throw new InvalidArgumentException(
'\'' + name + '\' is a singular relation, received type: \'' + value.constructor.name + '\'.'
);
}
if (isCollectionWithModels(value) && !ModelCollection.isModelCollection(value)) {
value = new ModelCollection(value.toArray());
}
if (isModelArray) {
value = new ModelCollection(value as T[]);
}
if (value instanceof HasRelations) {
if (!isSingularRelationType) {
value = new ModelCollection([value as T]);
} else {
if (relationType === 'belongsTo') {
// set attribute to ensure sync between the foreign key and the given value
this.setAttribute(value.guessForeignKeyName(), (value as T).getKey());
}
}
}
this.relations[name] = value as Model | ModelCollection<Model>;
this.createDescriptor(name);
return this;
}
let relatedCtor = ((this[start(name, this.relationMethodPrefix)] as CallableFunction)() as T)
.constructor as typeof Model;
let relation: Model | ModelCollection<Model>;
// set up the relations by calling the constructor of the related models
if (Array.isArray(value) || Collection.isCollection<Attributes>(value)) {
if (isSingularRelationType) {
throw new InvalidArgumentException(
'\'' + name + '\' is a singular relation, received type: \''
+ (Array.isArray(value) ? Array.name : Collection.name) + '\'.'
);
}
const collection = new ModelCollection;
value.forEach(modelData => collection.push(relatedCtor.make(modelData)));
relation = collection;
} else {
const model = relatedCtor.make(value);
if (relationType === 'belongsTo') {
// set attribute to ensure sync between the foreign key and the given value
this.setAttribute(model.guessForeignKeyName(), model.getKey());
}
if (isSingularRelationType) {
if (relationType === 'morphTo') {
let cb = this.morphToCb as MorphToCallback<this> | undefined;
if (!cb) {
// this model might not have the callback set, call the relation to obtain it
const modelWithCb = (this[
start(name, this.relationMethodPrefix)
] as CallableFunction)() as this;
// this could be any type, but it's filtered out in the below type check
cb = modelWithCb.morphToCb as typeof cb;
}
if (typeof cb !== 'function') {
throw new InvalidArgumentException(
'The morphTo relation was called with invalid argument type.'
);
}
relatedCtor = cb(this, value);
relation = relatedCtor.make(value);
delete this.morphToCb;
} else {
relation = model;
}
} else {
relation = new ModelCollection([model]);
}
}
this.relations[name] = relation as Model;
this.createDescriptor(name);
return this;
}
/**
* Remove the relation and its magic access if set.
*
* @param {string} name
*
* @return {this}
*/
public removeRelation(name: string): this {
name = this.removeRelationPrefix(name);
delete this.relations[name];
if (Object.getOwnPropertyDescriptor(this, name) // it is on this object
&& !(this[name] instanceof Function) // it isn't a function
&& this.relationDefined(name) // it has the corresponding relation method definition
) {
delete this[name];
}
return this;
}
/**
* Get all the relations.
*
* @return {object}
*/
public getRelations(): Record<string, (Model | ModelCollection<Model>)> {
return cloneDeep(this.relations);
}
/**
* Guess the foreign key name that would be used to reference this model.
*
* @return {string}
*/
public guessForeignKeyName(): string {
return this.setStringCase(
snake((this as unknown as Model).getName()).toLowerCase()
+ '_'
+ (this as unknown as Model).getKeyName()
);
}
/**
* Remove the prefix from the given string if set.
*
* @param {string} name
*
* @private
*
* @return {string}
*/
private removeRelationPrefix(name: string): string {
return name.startsWith(this.relationMethodPrefix) ? name.slice(this.relationMethodPrefix.length) : name;
}
/**
* Add the relation type onto the model.
*
* @param {Model} model
* @param {'belongsTo'|'belongsToMany'|'hasOne'|'hasMany'|'morphTo'|'morphMany'|'morphOne'} relationType
*
* @private
*
* @return {void}
*/
private static configureRelationType<T extends Model>(
model: T,
relationType: Relation
): asserts model is T & { _relationType: Readonly<Relation> } {
Object.defineProperty(model, '_relationType', {
configurable: false,
enumerable: false,
writable: false,
value: relationType
});
}
/**
* Set the endpoint to a nested url structure.
*
* @param {Model|Model[]} models
*
* @return this
*/
public for(models: MaybeArray<Model | (new () => Model)>): this {
models = Array.isArray(models) ? models : [models];
this.resetEndpoint();
let endpoint = '';
models.forEach((model) => {
if (!(model instanceof HasRelations)) {
model = new model;
}
endpoint += model.getEndpoint() + '/' + (model.getKey() ? String(model.getKey()) + '/' : '');
});
this.setEndpoint(endpoint + this.getEndpoint());
return this;
}
/**
* Set the endpoint on the correct model for querying.
*
* @param {Model} related
* @param {string=} foreignKey
*
* @return {Model}
*/
public belongsTo<T extends Model>(related: new() => T, foreignKey?: string): T {
const relatedModel = new related();
foreignKey = foreignKey ?? relatedModel.guessForeignKeyName();
const foreignKeyValue = this.getAttribute(foreignKey);
if (!foreignKeyValue) {
throw new LogicException(
'\'' + (this as unknown as Model).getName() + '\' doesn\'t have \'' + foreignKey + '\' defined.'
);
}
HasRelations.configureRelationType(relatedModel, 'belongsTo');
return relatedModel.setEndpoint(finish(relatedModel.getEndpoint(), '/') + String(foreignKeyValue));
}
/**
* Set the endpoint on the correct model for querying.
*
* @param {Model} related
* @param {string=} relationName - The name of the relation on the backend.
*
* @return {Model}
*/
public belongsToMany<T extends Model>(related: new() => T, relationName?: string): T {
const relatedModel = new related();
HasRelations.configureRelationType(relatedModel, 'belongsToMany');
relationName = relationName ?? plural((this as unknown as Model).getName()).toLowerCase();
return relatedModel.where(
relationName + '.' + (this as unknown as Model).getKeyName(),
'=',
(this as unknown as Model).getKey()
);
}
/**
* Set the endpoint on the correct model for querying.
*
* @param {Model} related
* @param {string=} foreignKey
*
* @return {Model}
*/
public hasOne<T extends Model>(related: new() => T, foreignKey: string = this.guessForeignKeyName()): T {
const relatedModel = new related();
HasRelations.configureRelationType(relatedModel, 'hasOne');
relatedModel.setAttribute(foreignKey, (this as unknown as Model).getKey());
relatedModel.hasOneOrManyParentKeyName = foreignKey;
return relatedModel.where(foreignKey, '=', (this as unknown as Model).getKey());
}
/**
* Set the endpoint on the correct model for querying.
*
* @param {Model} related
* @param {string=} foreignKey
*
* @return {Model}
*/
public hasMany<T extends Model>(related: new() => T, foreignKey: string = this.guessForeignKeyName()): T {
const relatedModel = new related();
HasRelations.configureRelationType(relatedModel, 'hasMany');
relatedModel.setAttribute(foreignKey, (this as unknown as Model).getKey());
relatedModel.hasOneOrManyParentKeyName = foreignKey;
return relatedModel.where(foreignKey, '=', (this as unknown as Model).getKey());
}
/**
* Set the endpoint on the correct model for querying.
*
* @param {Model} related
* @param {string=} morphName
*
* @return {Model}
*/
public morphMany<T extends Model>(related: new() => T, morphName?: string): T {
const relatedModel = new related();
const morphs = relatedModel.getMorphs();
HasRelations.configureRelationType(relatedModel, 'morphMany');
return relatedModel
.where(morphs.type, '=', morphName ?? (this as unknown as Model).getName())
.where(morphs.id, '=', (this as unknown as Model).getKey());
}
/**
* Set the endpoint on the correct model for querying.
*
* @param {Model} related
* @param {string=} morphName
*
* @return {Model}
*/
public morphOne<T extends Model>(related: new() => T, morphName?: string): T {
const relatedModel = new related();
const morphs = relatedModel.getMorphs();
HasRelations.configureRelationType(relatedModel, 'morphOne');
return relatedModel
.where(morphs.type, '=', morphName ?? (this as unknown as Model).getName())
.where(morphs.id, '=', (this as unknown as Model).getKey());
}
/**
* Add a constraint for the next query to return all relation.
*
* @param cb - Callback that returns a model that this morphs to.
* @param relationName - The name of the relation to be called. E.g.: `'commentable'`
*
* @example
* public $contractable(): this {
* return this.morphTo<Team | User>((self, _data) => {
* return self.contractableType === 'team' ? Team : User;
* });
* }
*
* @return {Model}
*/
public morphTo<T extends Model>(
cb: MorphToCallback<this, T>,
relationName?: string
): this {
relationName = relationName ?? this.getMorphs().id.slice(0, - '_id'.length);
const thisModel = new (this.constructor as typeof Model)().with([relationName]);
thisModel.setEndpoint(finish(thisModel.getEndpoint(), '/') + String((this as unknown as Model).getKey()));
HasRelations.configureRelationType(thisModel, 'morphTo');
Object.defineProperty(thisModel, 'morphToCb', {
configurable: true,
enumerable: false,
writable: false,
value: cb
});
return thisModel as unknown as this;
}
/**
* Get the polymorphic column names.
*
* @param {string=} name
*/
protected getMorphs(name?: string): Record<'id' | 'type', string> {
name = name ?? finish((this as unknown as Model).getName().toLowerCase(), 'able');
return { id: name + '_id', type: name + '_type' };
}
/**
* Throw an error if the model does not exist before calling the specified method.
*
* @param {string} methodName
*
* @protected
*
* @internal
*/
protected throwIfModelDoesntExistsWhenCalling(methodName: string): void {
if (!(this as unknown as Model).exists) {
throw new LogicException(
'Attempted to call ' + methodName + ' on \'' + (this as unknown as Model).getName()
+ '\' when it has not been persisted yet or it has been soft deleted.'
);
}
}
}