-
Notifications
You must be signed in to change notification settings - Fork 362
/
Copy pathrelation-definition.js
3509 lines (3066 loc) · 108 KB
/
relation-definition.js
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright IBM Corp. 2014,2019. All Rights Reserved.
// Node module: loopback-datasource-juggler
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
/*!
* Dependencies
*/
const assert = require('assert');
const util = require('util');
const async = require('async');
const utils = require('./utils');
const i8n = require('inflection');
const defineScope = require('./scope.js').defineScope;
const g = require('strong-globalize')();
const mergeQuery = utils.mergeQuery;
const idEquals = utils.idEquals;
const idsHaveDuplicates = utils.idsHaveDuplicates;
const ModelBaseClass = require('./model.js');
const applyFilter = require('./connectors/memory').applyFilter;
const ValidationError = require('./validations.js').ValidationError;
const deprecated = require('depd')('loopback-datasource-juggler');
const debug = require('debug')('loopback:relations');
const RelationTypes = {
belongsTo: 'belongsTo',
hasMany: 'hasMany',
hasOne: 'hasOne',
hasAndBelongsToMany: 'hasAndBelongsToMany',
referencesMany: 'referencesMany',
embedsOne: 'embedsOne',
embedsMany: 'embedsMany',
};
const RelationClasses = {
belongsTo: BelongsTo,
hasMany: HasMany,
hasManyThrough: HasManyThrough,
hasOne: HasOne,
hasAndBelongsToMany: HasAndBelongsToMany,
referencesMany: ReferencesMany,
embedsOne: EmbedsOne,
embedsMany: EmbedsMany,
};
exports.Relation = Relation;
exports.RelationDefinition = RelationDefinition;
exports.RelationTypes = RelationTypes;
exports.RelationClasses = RelationClasses;
exports.HasMany = HasMany;
exports.HasManyThrough = HasManyThrough;
exports.HasOne = HasOne;
exports.HasAndBelongsToMany = HasAndBelongsToMany;
exports.BelongsTo = BelongsTo;
exports.ReferencesMany = ReferencesMany;
exports.EmbedsOne = EmbedsOne;
exports.EmbedsMany = EmbedsMany;
function normalizeType(type) {
if (!type) {
return type;
}
const t1 = type.toLowerCase();
for (const t2 in RelationTypes) {
if (t2.toLowerCase() === t1) {
return t2;
}
}
return null;
}
function extendScopeMethods(definition, scopeMethods, ext) {
let customMethods = [];
let relationClass = RelationClasses[definition.type];
if (definition.type === RelationTypes.hasMany && definition.modelThrough) {
relationClass = RelationClasses.hasManyThrough;
}
if (typeof ext === 'function') {
customMethods = ext.call(definition, scopeMethods, relationClass);
} else if (typeof ext === 'object') {
function createFunc(definition, relationMethod) {
return function() {
const relation = new relationClass(definition, this);
return relationMethod.apply(relation, arguments);
};
}
for (const key in ext) {
const relationMethod = ext[key];
const method = scopeMethods[key] = createFunc(definition, relationMethod);
if (relationMethod.shared) {
sharedMethod(definition, key, method, relationMethod);
}
customMethods.push(key);
}
}
return [].concat(customMethods || []);
}
function bindRelationMethods(relation, relationMethod, definition) {
const methods = definition.methods || {};
Object.keys(methods).forEach(function(m) {
if (typeof methods[m] !== 'function') return;
relationMethod[m] = methods[m].bind(relation);
});
}
function preventFkOverride(inst, data, fkProp) {
if (!fkProp) return undefined;
if (data[fkProp] !== undefined && !idEquals(data[fkProp], inst[fkProp])) {
return new Error(g.f(
'Cannot override foreign key %s from %s to %s',
fkProp,
inst[fkProp],
data[fkProp],
));
}
}
/**
* Relation definition class. Use to define relationships between models.
* @param {Object} definition
* @class RelationDefinition
*/
function RelationDefinition(definition) {
if (!(this instanceof RelationDefinition)) {
return new RelationDefinition(definition);
}
definition = definition || {};
this.name = definition.name;
assert(this.name, 'Relation name is missing');
this.type = normalizeType(definition.type);
assert(this.type, 'Invalid relation type: ' + definition.type);
this.modelFrom = definition.modelFrom;
assert(this.modelFrom, 'Source model is required');
this.keyFrom = definition.keyFrom;
this.modelTo = definition.modelTo;
this.keyTo = definition.keyTo;
this.polymorphic = definition.polymorphic;
if (typeof this.polymorphic !== 'object') {
assert(this.modelTo, 'Target model is required');
}
this.modelThrough = definition.modelThrough;
this.keyThrough = definition.keyThrough;
this.multiple = definition.multiple;
this.properties = definition.properties || {};
this.options = definition.options || {};
this.scope = definition.scope;
this.embed = definition.embed === true;
this.methods = definition.methods || {};
}
RelationDefinition.prototype.toJSON = function() {
const polymorphic = typeof this.polymorphic === 'object';
let modelToName = this.modelTo && this.modelTo.modelName;
if (!modelToName && polymorphic && this.type === 'belongsTo') {
modelToName = '<polymorphic>';
}
const json = {
name: this.name,
type: this.type,
modelFrom: this.modelFrom.modelName,
keyFrom: this.keyFrom,
modelTo: modelToName,
keyTo: this.keyTo,
multiple: this.multiple,
};
if (this.modelThrough) {
json.modelThrough = this.modelThrough.modelName;
json.keyThrough = this.keyThrough;
}
if (polymorphic) {
json.polymorphic = this.polymorphic;
}
return json;
};
/**
* Define a relation scope method
* @param {String} name of the method
* @param {Function} function to define
*/
RelationDefinition.prototype.defineMethod = function(name, fn) {
const relationClass = RelationClasses[this.type];
const relationName = this.name;
const modelFrom = this.modelFrom;
const definition = this;
let method;
if (definition.multiple) {
const scope = this.modelFrom.scopes[this.name];
if (!scope) throw new Error(g.f('Unknown relation {{scope}}: %s', this.name));
method = scope.defineMethod(name, function() {
const relation = new relationClass(definition, this);
return fn.apply(relation, arguments);
});
} else {
definition.methods[name] = fn;
method = function() {
const rel = this[relationName];
return rel[name].apply(rel, arguments);
};
}
if (method && fn.shared) {
sharedMethod(definition, name, method, fn);
modelFrom.prototype['__' + name + '__' + relationName] = method;
}
return method;
};
/**
* Apply the configured scope to the filter/query object.
* @param {Object} modelInstance
* @param {Object} filter (where, order, limit, fields, ...)
*/
RelationDefinition.prototype.applyScope = function(modelInstance, filter) {
filter = filter || {};
filter.where = filter.where || {};
if ((this.type !== 'belongsTo' || this.type === 'hasOne') &&
typeof this.polymorphic === 'object') { // polymorphic
const discriminator = this.polymorphic.discriminator;
if (this.polymorphic.invert) {
filter.where[discriminator] = this.modelTo.modelName;
} else {
filter.where[discriminator] = this.modelFrom.modelName;
}
}
let scope;
if (typeof this.scope === 'function') {
scope = this.scope.call(this, modelInstance, filter);
} else {
scope = this.scope;
}
if (typeof scope === 'object') {
mergeQuery(filter, scope);
}
};
/**
* Apply the configured properties to the target object.
* @param {Object} modelInstance
* @param {Object} target
*/
RelationDefinition.prototype.applyProperties = function(modelInstance, obj) {
let source = modelInstance, target = obj;
if (this.options.invertProperties) {
source = obj;
target = modelInstance;
}
if (this.options.embedsProperties) {
target = target.__data[this.name] = {};
target[this.keyTo] = source[this.keyTo];
}
let k, key;
if (typeof this.properties === 'function') {
const data = this.properties.call(this, source, target);
for (k in data) {
target[k] = data[k];
}
} else if (Array.isArray(this.properties)) {
for (k = 0; k < this.properties.length; k++) {
key = this.properties[k];
target[key] = source[key];
}
} else if (typeof this.properties === 'object') {
for (k in this.properties) {
key = this.properties[k];
target[key] = source[k];
}
}
if ((this.type !== 'belongsTo' || this.type === 'hasOne') &&
typeof this.polymorphic === 'object') { // polymorphic
const discriminator = this.polymorphic.discriminator;
if (this.polymorphic.invert) {
target[discriminator] = this.modelTo.modelName;
} else {
target[discriminator] = this.modelFrom.modelName;
}
}
};
/**
* A relation attaching to a given model instance
* @param {RelationDefinition|Object} definition
* @param {Object} modelInstance
* @returns {Relation}
* @constructor
* @class Relation
*/
function Relation(definition, modelInstance) {
if (!(this instanceof Relation)) {
return new Relation(definition, modelInstance);
}
if (!(definition instanceof RelationDefinition)) {
definition = new RelationDefinition(definition);
}
this.definition = definition;
this.modelInstance = modelInstance;
}
Relation.prototype.resetCache = function(cache) {
cache = cache || undefined;
this.modelInstance.__cachedRelations[this.definition.name] = cache;
};
Relation.prototype.getCache = function() {
return this.modelInstance.__cachedRelations[this.definition.name];
};
Relation.prototype.callScopeMethod = function(methodName) {
const args = Array.prototype.slice.call(arguments, 1);
const modelInstance = this.modelInstance;
const rel = modelInstance[this.definition.name];
if (rel && typeof rel[methodName] === 'function') {
return rel[methodName].apply(rel, args);
} else {
throw new Error(g.f('Unknown scope method: %s', methodName));
}
};
/**
* Fetch the related model(s) - this is a helper method to unify access.
* @param (Boolean|Object} condOrRefresh refresh or conditions object
* @param {Object} [options] Options
* @param {Function} cb callback
*/
Relation.prototype.fetch = function(condOrRefresh, options, cb) {
this.modelInstance[this.definition.name].apply(this.modelInstance, arguments);
};
/**
* HasMany subclass
* @param {RelationDefinition|Object} definition
* @param {Object} modelInstance
* @returns {HasMany}
* @constructor
* @class HasMany
*/
function HasMany(definition, modelInstance) {
if (!(this instanceof HasMany)) {
return new HasMany(definition, modelInstance);
}
assert(definition.type === RelationTypes.hasMany);
Relation.apply(this, arguments);
}
util.inherits(HasMany, Relation);
HasMany.prototype.removeFromCache = function(id) {
const cache = this.modelInstance.__cachedRelations[this.definition.name];
const idName = this.definition.modelTo.definition.idName();
if (Array.isArray(cache)) {
for (let i = 0, n = cache.length; i < n; i++) {
if (idEquals(cache[i][idName], id)) {
return cache.splice(i, 1);
}
}
}
return null;
};
HasMany.prototype.addToCache = function(inst) {
if (!inst) {
return;
}
let cache = this.modelInstance.__cachedRelations[this.definition.name];
if (cache === undefined) {
cache = this.modelInstance.__cachedRelations[this.definition.name] = [];
}
const idName = this.definition.modelTo.definition.idName();
if (Array.isArray(cache)) {
for (let i = 0, n = cache.length; i < n; i++) {
if (idEquals(cache[i][idName], inst[idName])) {
cache[i] = inst;
return;
}
}
cache.push(inst);
}
};
/**
* HasManyThrough subclass
* @param {RelationDefinition|Object} definition
* @param {Object} modelInstance
* @returns {HasManyThrough}
* @constructor
* @class HasManyThrough
*/
function HasManyThrough(definition, modelInstance) {
if (!(this instanceof HasManyThrough)) {
return new HasManyThrough(definition, modelInstance);
}
assert(definition.type === RelationTypes.hasMany);
assert(definition.modelThrough);
HasMany.apply(this, arguments);
}
util.inherits(HasManyThrough, HasMany);
/**
* BelongsTo subclass
* @param {RelationDefinition|Object} definition
* @param {Object} modelInstance
* @returns {BelongsTo}
* @constructor
* @class BelongsTo
*/
function BelongsTo(definition, modelInstance) {
if (!(this instanceof BelongsTo)) {
return new BelongsTo(definition, modelInstance);
}
assert(definition.type === RelationTypes.belongsTo);
Relation.apply(this, arguments);
}
util.inherits(BelongsTo, Relation);
/**
* HasAndBelongsToMany subclass
* @param {RelationDefinition|Object} definition
* @param {Object} modelInstance
* @returns {HasAndBelongsToMany}
* @constructor
* @class HasAndBelongsToMany
*/
function HasAndBelongsToMany(definition, modelInstance) {
if (!(this instanceof HasAndBelongsToMany)) {
return new HasAndBelongsToMany(definition, modelInstance);
}
assert(definition.type === RelationTypes.hasAndBelongsToMany);
Relation.apply(this, arguments);
}
util.inherits(HasAndBelongsToMany, Relation);
/**
* HasOne subclass
* @param {RelationDefinition|Object} definition
* @param {Object} modelInstance
* @returns {HasOne}
* @constructor
* @class HasOne
*/
function HasOne(definition, modelInstance) {
if (!(this instanceof HasOne)) {
return new HasOne(definition, modelInstance);
}
assert(definition.type === RelationTypes.hasOne);
Relation.apply(this, arguments);
}
util.inherits(HasOne, Relation);
/**
* EmbedsOne subclass
* @param {RelationDefinition|Object} definition
* @param {Object} modelInstance
* @returns {EmbedsOne}
* @constructor
* @class EmbedsOne
*/
function EmbedsOne(definition, modelInstance) {
if (!(this instanceof EmbedsOne)) {
return new EmbedsOne(definition, modelInstance);
}
assert(definition.type === RelationTypes.embedsOne);
Relation.apply(this, arguments);
}
util.inherits(EmbedsOne, Relation);
/**
* EmbedsMany subclass
* @param {RelationDefinition|Object} definition
* @param {Object} modelInstance
* @returns {EmbedsMany}
* @constructor
* @class EmbedsMany
*/
function EmbedsMany(definition, modelInstance) {
if (!(this instanceof EmbedsMany)) {
return new EmbedsMany(definition, modelInstance);
}
assert(definition.type === RelationTypes.embedsMany);
Relation.apply(this, arguments);
}
util.inherits(EmbedsMany, Relation);
/**
* ReferencesMany subclass
* @param {RelationDefinition|Object} definition
* @param {Object} modelInstance
* @returns {ReferencesMany}
* @constructor
* @class ReferencesMany
*/
function ReferencesMany(definition, modelInstance) {
if (!(this instanceof ReferencesMany)) {
return new ReferencesMany(definition, modelInstance);
}
assert(definition.type === RelationTypes.referencesMany);
Relation.apply(this, arguments);
}
util.inherits(ReferencesMany, Relation);
/*!
* Find the relation by foreign key
* @param {*} foreignKey The foreign key
* @returns {Array} The array of matching relation objects
*/
function findBelongsTo(modelFrom, modelTo, keyTo) {
return Object.keys(modelFrom.relations)
.map(function(k) { return modelFrom.relations[k]; })
.filter(function(rel) {
return (rel.type === RelationTypes.belongsTo &&
rel.modelTo === modelTo &&
(keyTo === undefined || rel.keyTo === keyTo));
})
.map(function(rel) {
return rel.keyFrom;
});
}
/*!
* Look up a model by name from the list of given models
* @param {Object} models Models keyed by name
* @param {String} modelName The model name
* @returns {*} The matching model class
*/
function lookupModel(models, modelName) {
if (models[modelName]) {
return models[modelName];
}
const lookupClassName = modelName.toLowerCase();
for (const name in models) {
if (name.toLowerCase() === lookupClassName) {
return models[name];
}
}
}
/*
* @param {Object} modelFrom Instance of the 'from' model
* @param {Object|String} modelToRef Reference to Model object to which you are
* creating the relation: model instance, model name, or name of relation to model.
* @param {Object} params The relation params
* @param {Boolean} singularize Whether the modelToRef should be singularized when
* looking-up modelTo
* @return {Object} modelTo Instance of the 'to' model
*/
function lookupModelTo(modelFrom, modelToRef, params, singularize) {
let modelTo;
if (typeof modelToRef !== 'string') {
// modelToRef might already be an instance of model
modelTo = modelToRef;
} else {
// lookup modelTo based on relation params and modelToRef
let modelToName;
modelTo = params.model || modelToRef; // modelToRef might be modelTo name
if (typeof modelTo === 'string') {
// lookup modelTo by name
modelToName = modelTo;
modelToName = (singularize ? i8n.singularize(modelToName) : modelToName).toLowerCase();
modelTo = lookupModel(modelFrom.dataSource.modelBuilder.models, modelToName);
}
if (!modelTo) {
// lookup by modelTo name was not successful. Now looking-up by relationTo name
const relationToName = params.as || modelToRef; // modelToRef might be relationTo name
modelToName = (singularize ? i8n.singularize(relationToName) : relationToName).toLowerCase();
modelTo = lookupModel(modelFrom.dataSource.modelBuilder.models, modelToName);
}
}
if (typeof modelTo !== 'function') {
throw new Error(g.f('Could not find relation %s for model %s', params.as, modelFrom.modelName));
}
return modelTo;
}
/*
* Normalize relation's parameter `as`
* @param {Object} params The relation params
* @param {String} relationName The relation name
* @returns {Object} The normalized parameters
* NOTE: normalizeRelationAs() mutates the params object
*/
function normalizeRelationAs(params, relationName) {
if (typeof relationName === 'string') {
params.as = params.as || relationName;
}
return params;
}
/*
* Normalize relation's polymorphic parameters
* @param {Object|String|Boolean} polymorphic Param `polymorphic` of the relation.
* @param {String} relationName The name of the relation we are currently setting up.
* @returns {Object} The normalized parameters
*/
function normalizePolymorphic(polymorphic, relationName) {
assert(polymorphic, 'polymorphic param can\'t be false, null or undefined');
assert(!Array.isArray(polymorphic, 'unexpected type for polymorphic param: \'Array\''));
let selector;
if (typeof polymorphic === 'string') {
// relation type is different from belongsTo (hasMany, hasManyThrough, hasAndBelongsToMany, ...)
// polymorphic is the name of the matching belongsTo relation from modelTo to modelFrom
selector = polymorphic;
}
if (polymorphic === true) {
// relation type is belongsTo: the relation name is used as the polymorphic selector
selector = relationName;
}
// NOTE: use of `polymorphic.as` keyword will be deprecated in LoopBack.next
// to avoid confusion with keyword `as` used at the root of the relation definition object
// It is replaced with the `polymorphic.selector` keyword
if (typeof polymorphic == 'object') {
selector = polymorphic.selector || polymorphic.as;
}
// relationName is eventually used as selector if provided and selector not already defined
// it ultimately defaults to 'reference'
selector = selector || relationName || 'reference';
// make sure polymorphic is an object
if (typeof polymorphic !== 'object') {
polymorphic = {};
}
polymorphic.selector = selector;
polymorphic.foreignKey = polymorphic.foreignKey || i8n.camelize(selector + '_id', true); // defaults to {{selector}}Id
polymorphic.discriminator = polymorphic.discriminator || i8n.camelize(selector + '_type', true); // defaults to {{selectorName}}Type
return polymorphic;
}
/**
* Define a "one to many" relationship by specifying the model name
*
* Examples:
* ```
* User.hasMany(Post, {as: 'posts', foreignKey: 'authorId'});
* ```
*
* ```
* Book.hasMany(Chapter);
* ```
* Or, equivalently:
* ```
* Book.hasMany('chapters', {model: Chapter});
* ```
* @param {Model} modelFrom Source model class
* @param {Object|String} modelToRef Reference to Model object to which you are
* creating the relation: model instance, model name, or name of relation to model.
* @options {Object} params Configuration parameters; see below.
* @property {String} as Name of the property in the referring model that corresponds to the foreign key field in the related model.
* @property {String} foreignKey Property name of foreign key field.
* @property {Object} model Model object
*/
RelationDefinition.hasMany = function hasMany(modelFrom, modelToRef, params) {
const thisClassName = modelFrom.modelName;
params = params || {};
normalizeRelationAs(params, modelToRef);
const modelTo = lookupModelTo(modelFrom, modelToRef, params, true);
const relationName = params.as || i8n.camelize(modelTo.pluralModelName, true);
let fk = params.foreignKey || i8n.camelize(thisClassName + '_id', true);
let keyThrough = params.keyThrough || i8n.camelize(modelTo.modelName + '_id', true);
const pkName = params.primaryKey || modelFrom.dataSource.idName(modelFrom.modelName) || 'id';
let discriminator, polymorphic;
if (params.polymorphic) {
polymorphic = normalizePolymorphic(params.polymorphic, relationName);
if (params.invert) {
polymorphic.invert = true;
keyThrough = polymorphic.foreignKey;
}
discriminator = polymorphic.discriminator;
if (!params.invert) {
fk = polymorphic.foreignKey;
}
if (!params.through) {
modelTo.dataSource.defineProperty(modelTo.modelName, discriminator, {type: 'string', index: true});
}
}
const definition = new RelationDefinition({
name: relationName,
type: RelationTypes.hasMany,
modelFrom: modelFrom,
keyFrom: pkName,
keyTo: fk,
modelTo: modelTo,
multiple: true,
properties: params.properties,
scope: params.scope,
options: params.options,
keyThrough: keyThrough,
polymorphic: polymorphic,
});
definition.modelThrough = params.through;
modelFrom.relations[relationName] = definition;
if (!params.through) {
// obviously, modelTo should have attribute called `fk`
// for polymorphic relations, it is assumed to share the same fk type for all
// polymorphic models
modelTo.dataSource.defineForeignKey(modelTo.modelName, fk, modelFrom.modelName, pkName);
}
const scopeMethods = {
findById: scopeMethod(definition, 'findById'),
destroy: scopeMethod(definition, 'destroyById'),
updateById: scopeMethod(definition, 'updateById'),
exists: scopeMethod(definition, 'exists'),
};
const findByIdFunc = scopeMethods.findById;
modelFrom.prototype['__findById__' + relationName] = findByIdFunc;
const destroyByIdFunc = scopeMethods.destroy;
modelFrom.prototype['__destroyById__' + relationName] = destroyByIdFunc;
const updateByIdFunc = scopeMethods.updateById;
modelFrom.prototype['__updateById__' + relationName] = updateByIdFunc;
const existsByIdFunc = scopeMethods.exists;
modelFrom.prototype['__exists__' + relationName] = existsByIdFunc;
if (definition.modelThrough) {
scopeMethods.create = scopeMethod(definition, 'create');
scopeMethods.add = scopeMethod(definition, 'add');
scopeMethods.remove = scopeMethod(definition, 'remove');
const addFunc = scopeMethods.add;
modelFrom.prototype['__link__' + relationName] = addFunc;
const removeFunc = scopeMethods.remove;
modelFrom.prototype['__unlink__' + relationName] = removeFunc;
} else {
scopeMethods.create = scopeMethod(definition, 'create');
scopeMethods.build = scopeMethod(definition, 'build');
}
const customMethods = extendScopeMethods(definition, scopeMethods, params.scopeMethods);
for (let i = 0; i < customMethods.length; i++) {
const methodName = customMethods[i];
const method = scopeMethods[methodName];
if (typeof method === 'function' && method.shared === true) {
modelFrom.prototype['__' + methodName + '__' + relationName] = method;
}
}
// Mix the property and scoped methods into the prototype class
defineScope(modelFrom.prototype, params.through || modelTo, relationName, function() {
const filter = {};
filter.where = {};
filter.where[fk] = this[pkName];
definition.applyScope(this, filter);
if (definition.modelThrough) {
let throughRelationName;
// find corresponding belongsTo relations from through model as collect
for (const r in definition.modelThrough.relations) {
const relation = definition.modelThrough.relations[r];
// should be a belongsTo and match modelTo and keyThrough
// if relation is polymorphic then check keyThrough only
if (relation.type === RelationTypes.belongsTo &&
(relation.polymorphic && !relation.modelTo || relation.modelTo === definition.modelTo) &&
(relation.keyFrom === definition.keyThrough)
) {
throughRelationName = relation.name;
break;
}
}
if (definition.polymorphic && definition.polymorphic.invert) {
filter.collect = definition.polymorphic.selector;
filter.include = filter.collect;
} else {
filter.collect = throughRelationName || i8n.camelize(modelTo.modelName, true);
filter.include = filter.collect;
}
}
return filter;
}, scopeMethods, definition.options);
return definition;
};
function scopeMethod(definition, methodName) {
let relationClass = RelationClasses[definition.type];
if (definition.type === RelationTypes.hasMany && definition.modelThrough) {
relationClass = RelationClasses.hasManyThrough;
}
const method = function() {
const relation = new relationClass(definition, this);
return relation[methodName].apply(relation, arguments);
};
const relationMethod = relationClass.prototype[methodName];
if (relationMethod.shared) {
sharedMethod(definition, methodName, method, relationMethod);
}
return method;
}
function sharedMethod(definition, methodName, method, relationMethod) {
method.shared = true;
method.accepts = relationMethod.accepts;
method.returns = relationMethod.returns;
method.http = relationMethod.http;
method.description = relationMethod.description;
}
/**
* Find a related item by foreign key
* @param {*} fkId The foreign key
* @param {Object} [options] Options
* @param {Function} cb The callback function
*/
HasMany.prototype.findById = function(fkId, options, cb) {
if (typeof options === 'function' && cb === undefined) {
cb = options;
options = {};
}
const modelTo = this.definition.modelTo;
const modelFrom = this.definition.modelFrom;
const fk = this.definition.keyTo;
const pk = this.definition.keyFrom;
const modelInstance = this.modelInstance;
const idName = this.definition.modelTo.definition.idName();
const filter = {};
filter.where = {};
filter.where[idName] = fkId;
filter.where[fk] = modelInstance[pk];
cb = cb || utils.createPromiseCallback();
if (filter.where[fk] === undefined) {
// Foreign key is undefined
process.nextTick(cb);
return cb.promise;
}
this.definition.applyScope(modelInstance, filter);
modelTo.findOne(filter, options, function(err, inst) {
if (err) {
return cb(err);
}
if (!inst) {
err = new Error(g.f('No instance with {{id}} %s found for %s', fkId, modelTo.modelName));
err.statusCode = 404;
return cb(err);
}
// Check if the foreign key matches the primary key
if (inst[fk] != null && idEquals(inst[fk], modelInstance[pk])) {
cb(null, inst);
} else {
err = new Error(g.f('Key mismatch: %s.%s: %s, %s.%s: %s',
modelFrom.modelName, pk, modelInstance[pk], modelTo.modelName, fk, inst[fk]));
err.statusCode = 400;
cb(err);
}
});
return cb.promise;
};
/**
* Find a related item by foreign key
* @param {*} fkId The foreign key
* @param {Object} [options] Options
* @param {Function} cb The callback function
*/
HasMany.prototype.exists = function(fkId, options, cb) {
if (typeof options === 'function' && cb === undefined) {
cb = options;
options = {};
}
const fk = this.definition.keyTo;
const pk = this.definition.keyFrom;
const modelInstance = this.modelInstance;
cb = cb || utils.createPromiseCallback();
this.findById(fkId, function(err, inst) {
if (err) {
return cb(err);
}
if (!inst) {
return cb(null, false);
}
// Check if the foreign key matches the primary key
if (inst[fk] && inst[fk].toString() === modelInstance[pk].toString()) {
cb(null, true);
} else {
cb(null, false);
}
});
return cb.promise;
};
/**
* Update a related item by foreign key
* @param {*} fkId The foreign key
* @param {Object} Changes to the data
* @param {Object} [options] Options
* @param {Function} cb The callback function
*/
HasMany.prototype.updateById = function(fkId, data, options, cb) {
if (typeof options === 'function' && cb === undefined) {
cb = options;
options = {};
}
cb = cb || utils.createPromiseCallback();
const fk = this.definition.keyTo;
this.findById(fkId, options, function(err, inst) {
if (err) {
return cb && cb(err);
}
// Ensure Foreign Key cannot be changed!
const fkErr = preventFkOverride(inst, data, fk);
if (fkErr) return cb(fkErr);
inst.updateAttributes(data, options, cb);
});
return cb.promise;
};
/**
* Delete a related item by foreign key
* @param {*} fkId The foreign key
* @param {Object} [options] Options
* @param {Function} cb The callback function
*/
HasMany.prototype.destroyById = function(fkId, options, cb) {
if (typeof options === 'function' && cb === undefined) {
cb = options;
options = {};
}
cb = cb || utils.createPromiseCallback();
const self = this;
this.findById(fkId, options, function(err, inst) {
if (err) {
return cb(err);
}
self.removeFromCache(fkId);
inst.destroy(options, cb);
});
return cb.promise;
};
const throughKeys = function(definition) {
const modelThrough = definition.modelThrough;
const pk2 = definition.modelTo.definition.idName();
let fk1, fk2;
if (typeof definition.polymorphic === 'object') { // polymorphic
fk1 = definition.keyTo;
if (definition.polymorphic.invert) {
fk2 = definition.polymorphic.foreignKey;
} else {
fk2 = definition.keyThrough;
}
} else if (definition.modelFrom === definition.modelTo) {
return findBelongsTo(modelThrough, definition.modelTo, pk2).
sort(function(fk1, fk2) {
// Fix for bug - https://github.com/strongloop/loopback-datasource-juggler/issues/571
// Make sure that first key is mapped to modelFrom
// & second key to modelTo. Order matters
return (definition.keyTo === fk1) ? -1 : 1;
});
} else {
fk1 = findBelongsTo(modelThrough, definition.modelFrom,
definition.keyFrom)[0];
fk2 = findBelongsTo(modelThrough, definition.modelTo, pk2)[0];
}
return [fk1, fk2];
};