-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdata-mapping-extensions.js
More file actions
1011 lines (988 loc) · 47.4 KB
/
data-mapping-extensions.js
File metadata and controls
1011 lines (988 loc) · 47.4 KB
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
// MOST Web Framework 2.0 Codename Blueshift BSD-3-Clause license Copyright (c) 2017-2022, THEMOST LP All rights reserved
/*eslint no-var: "off"*/
// noinspection ES6ConvertVarToLetConst
var _ = require('lodash');
var {QueryUtils} = require('@themost/query');
var {QueryEntity} = require('@themost/query');
var {QueryField} = require('@themost/query');
var {DataError} = require('@themost/common')
var {hasOwnProperty} = require('./has-own-property');
var {isObjectDeep} = require('./is-object');
/**
* @param {Array<QueryField|*>} fields
* @param {string} name
* @return {*}
*/
function containsField(fields, name) {
return fields.find(function(field) {
if (field instanceof QueryField) {
return field.as() === name || field.getName() === name;
} else {
var f = Object.assign(new QueryField(), field);
return f.as() === name || f.getName() === name;
}
});
}
class DataMappingExtender {
constructor(mapping) {
this.mapping = mapping;
}
/**
* @param {DataQueryable} queryable
* @returns
*/
for(queryable) {
this.queryable = queryable;
return this;
}
getChildModel() {
if (this.queryable == null) {
return;
}
if (this._childModel != null) {
return this._childModel;
}
this._childModel = this.queryable.model.context.model(this.mapping.childModel);
return this._childModel;
}
getParentModel() {
if (this.queryable == null) {
return;
}
if (this._parentModel != null) {
return this._parentModel;
}
this._parentModel = this.queryable.model.context.model(this.mapping.parentModel);
return this._parentModel;
}
/**
* @param {*} items
* @returns {Promise|*}
*/
getParents(items) {
var thisArg = this;
var isSilent = false;
var thisQueryable = this.queryable;
var mapping = this.mapping;
return new Promise(function(resolve, reject) {
if (_.isNil(items)) {
return resolve();
}
var arr = _.isArray(items) ? items : [items];
if (arr.length === 0) {
return resolve();
}
if (_.isNil(thisQueryable)) {
return reject('The underlying data queryable cannot be empty at this context.');
}
if ((mapping.childModel !== thisQueryable.model.name) || (mapping.associationType!=='junction')) {
return resolve();
}
//get array of key values (for childs)
var values = arr.filter(function(x) {
return (typeof x[mapping.childField]!=='undefined')
&& (x[mapping.childField]!=null); })
.map(function(x) { return x[mapping.childField]
});
//query junction model
var HasParentJunction = require('./has-parent-junction').HasParentJunction;
var junction = new HasParentJunction(thisQueryable.model.convert({ }), mapping);
isSilent = !!thisQueryable.$silent;
junction.getBaseModel().where(mapping.associationValueField).in(values).flatten().silent(isSilent).all(function(err, junctions) {
if (err) {
return reject(err);
}
//get array of parent key values
values = _.intersection(junctions.map(function(x) { return x[mapping.associationObjectField] }));
//get parent model
var parentModel = thisArg.getParentModel();
//query parent with parent key values
parentModel.filter(mapping.options, function(err, q) {
if (err) {
return reject(err);
}
q.prepare();
//Important Backward compatibility issue (<1.8.0)
//Description: if $levels parameter is not defined then set the default value to 0.
if (typeof q.$levels === 'undefined') {
q.$levels = 0;
}
q.where(mapping.parentField).in(values);
//inherit silent mode
if (thisQueryable.$silent) {
q.silent();
}
if (q.query.hasFields() === false) {
q.select();
}
var parentField = thisArg.getParentModel().getAttribute(mapping.parentField);
var keyField = parentField.property || parentField.name;
// if query is a select statement
if (q.query.$fixed == null) {
// check if foreign key field exists in query
var selectEntity = q.model.viewAdapter;
if (Object.prototype.hasOwnProperty.call(q.query.$select, selectEntity)) {
/**
* @type {Array}
*/
var select = Object.getOwnPropertyDescriptor(q.query.$select, selectEntity).value;
// find foreign key key
var find = containsField(select, keyField);
// if foreign key field does not exist
if (find == null) {
// clone query
var q1 = q.clone().select(keyField);
// and select foreign key field
var select1 = Object.getOwnPropertyDescriptor(q1.query.$select, selectEntity).value;
if (Array.isArray(select1)) {
// append field to select fields
select.push.apply(select, select1);
}
}
}
}
//and finally query parent
q.getItems().then(function(parents){
//if result contains only one item
if (arr.length === 1) {
arr[0][mapping.refersTo] = parents;
return resolve();
}
//otherwise loop result array
arr.forEach(function(x) {
//get child (key value)
var childValue = x[mapping.childField];
//get parent(s)
var p = junctions.filter(function(y) { return (y[mapping.associationValueField]===childValue); }).map(function(r) { return r[mapping.associationObjectField]; });
//filter data and set property value (a filtered array of parent objects)
x[mapping.refersTo] = parents.filter(function(z) { return p.indexOf(z[mapping.parentField])>=0; });
});
return resolve();
}).catch(function(err) {
return reject(err);
});
});
});
});
}
/**
* @param {*} items
* @returns {Promise|*}
*/
getChildren(items) {
var thisArg = this;
var isSilent = false;
var thisQueryable = this.queryable;
var mapping = this.mapping;
return new Promise(function(resolve, reject) {
if (_.isNil(items)) {
return resolve();
}
var arr = _.isArray(items) ? items : [items];
if (arr.length === 0) {
return resolve();
}
if (_.isNil(thisQueryable)) {
return reject('The underlying data queryable cannot be empty at this context.');
}
if ((mapping.parentModel !== thisQueryable.model.name) || (mapping.associationType!=='junction')) {
return resolve();
}
var values = arr.filter(function(x) {
return (typeof x[mapping.parentField]!=='undefined') && (x[mapping.parentField]!=null);
}).map(function(x) {
return x[mapping.parentField];
});
if (_.isNil(mapping.childModel)) {
var DataObjectTag = require('./data-object-tag').DataObjectTag;
junction = new DataObjectTag(thisQueryable.model.convert({ }), mapping);
var objectField = junction.getObjectField();
var valueField = junction.getValueField();
isSilent = !!thisQueryable.$silent;
return junction.getBaseModel().where(objectField).in(values).flatten().silent(isSilent).select(objectField, valueField).all().then(function(items) {
arr.forEach(function(x) {
x[mapping.refersTo] = items.filter(function(y) {
return y[objectField]===x[mapping.parentField];
}).map(function (y) {
return y[valueField];
});
});
return resolve();
}).catch(function (err) {
return reject(err);
});
}
//create a dummy object
var DataObjectJunction = require('./data-object-junction').DataObjectJunction;
var junction = new DataObjectJunction(thisQueryable.model.convert({ }), mapping);
//query junction model
isSilent = !!thisQueryable.$silent;
return junction.getBaseModel().where(mapping.associationObjectField).in(values).silent(isSilent).flatten().getItems().then(function(junctions) {
//get array of child key values
var values = junctions.map(function(x) { return x[mapping.associationValueField] });
//get child model
var childModel = thisArg.getChildModel();
childModel.filter(mapping.options, function(err, q) {
if (err) {
return reject(err);
}
q.prepare();
//Important Backward compatibility issue (<1.8.0)
//Description: if $levels parameter is not defined then set the default value to 0.
if (typeof q.$levels === 'undefined') {
q.$levels = 0;
}
if (q.query.hasFields() === false) {
q.select();
}
//inherit silent mode
if (thisQueryable.$silent) {
q.silent();
}
var childField = thisArg.getChildModel().getAttribute(mapping.childField);
var keyField = childField.property || childField.name;
// if query is a select statement
if (q.query.$fixed == null) {
// check if foreign key field exists in query
var selectEntity = q.model.viewAdapter;
if (Object.prototype.hasOwnProperty.call(q.query.$select, selectEntity)) {
/**
* @type {Array}
*/
var select = Object.getOwnPropertyDescriptor(q.query.$select, selectEntity).value;
// find foreign key key
var find = containsField(select, keyField);
// if foreign key field does not exist
if (find == null) {
// clone query
var q1 = q.clone().select(keyField);
// and select foreign key field
var select1 = Object.getOwnPropertyDescriptor(q1.query.$select, selectEntity).value;
if (Array.isArray(select1)) {
// append field to select fields
select.push.apply(select, select1);
}
}
}
}
//append where statement for this operation
if (values.length===1) {
q.where(mapping.childField).equal(values[0]);
}
else {
q.where(mapping.childField).in(values);
}
//and finally query childs
var refersTo = thisQueryable.model.getAttribute(mapping.refersTo);
q.getItems().then(function(childs) {
//if result contains only one item
if (arr.length === 1) {
if (refersTo && (refersTo.multiplicity === 'ZeroOrOne' || refersTo.multiplicity === 'One')) {
arr[0][mapping.refersTo] = childs[0] != null ? childs[0] : null;
return resolve();
}
arr[0][mapping.refersTo] = childs;
return resolve();
}
//otherwise loop result array
arr.forEach(function(x) {
//get parent (key value)
var parentValue = x[mapping.parentField];
//get parent(s)
var p = junctions.filter(function(y) { return (y[mapping.associationObjectField]===parentValue); }).map(function(r) { return r[mapping.associationValueField]; });
//filter data and set property value (a filtered array of parent objects)
if (refersTo && (refersTo.multiplicity === 'ZeroOrOne' || refersTo.multiplicity === 'One')) {
// get only one child
x[mapping.refersTo] = childs.find(function(z) {
return p.indexOf(z[mapping.childField])>=0;
});
} else {
x[mapping.refersTo] = childs.filter(function(z) {
return p.indexOf(z[mapping.childField])>=0;
});
}
});
return resolve();
}).catch(function(err) {
return reject(err);
});
});
}).catch(function (err) {
return reject(err);
});
});
}
/**
* @param {*} items
* @returns {Promise|*}
*/
getAssociatedParents(items) {
var thisArg = this;
var thisQueryable = this.queryable;
var mapping = this.mapping;
return new Promise(function(resolve, reject) {
if (_.isNil(items)) {
return resolve();
}
var arr = _.isArray(items) ? items : [items];
if (arr.length === 0) {
return resolve();
}
if (_.isNil(thisQueryable)) {
return reject('The underlying data queryable cannot be empty at this context.');
}
if ((mapping.childModel !== thisQueryable.model.name) || (mapping.associationType!=='association')) {
return resolve();
}
thisArg.getParentModel().migrate(function(err) {
if (err) { return reject(err); }
var childField = thisQueryable.model.field(mapping.childField);
var keyField = childField.property || childField.name;
if (_.isNil(childField)) {
return reject('The specified field cannot be found on child model');
}
var childFieldType = thisQueryable.model.context.model(childField.type);
var values = _.intersection(_.map(_.filter(arr, function(x) {
return hasOwnProperty(x, keyField) && x[keyField] != null;
}), function (x) {
return x[keyField];
})).map(function(x) {
if (isObjectDeep(x)) {
if (childFieldType) {
return x[childFieldType.primaryKey];
}
throw new Error('The child item is an object but its type cannot determined.');
}
return x;
}).filter(function(x) {
return x != null;
});
if (values.length===0) {
return resolve();
}
thisArg.getParentModel().filter(mapping.options, function(err, q) {
if (err) {
return reject(err);
}
q.prepare();
//Important Backward compatibility issue (<1.8.0)
//Description: if $levels parameter is not defined then set the default value to 0.
if (typeof q.$levels === 'undefined') {
q.$levels = 0;
}
//inherit silent mode
if (thisQueryable.$silent) { q.silent(); }
//append where statement for this operation
q.where(mapping.parentField).in(values);
//set silent (?)
if (childField && childField.nested === true) {
q.silent();
}
q.getAllItems().then(function(parents) {
var iterator = function(x) {
var key = x[keyField];
var property = childField.property || childField.name;
if (property == null) {
throw new DataError( 'E_NULL', 'Child attribute cannot be empty', null, mapping.childModel, mapping.childField);
}
var find = parents.find(function(parent) {
return parent[mapping.parentField] === key;
});
// clone parent or set null
x[property] = find != null ? _.cloneDeep(find) : null;
};
if (Array.isArray(arr)) {
arr.forEach(iterator);
}
return resolve();
}).catch(function(err) {
return reject(err);
});
});
});
});
}
/**
* @param {*} items
* @returns {Promise|*}
*/
getAssociatedChildren(items) {
var thisArg = this;
var thisQueryable = this.queryable;
var mapping = this.mapping;
return new Promise(function(resolve, reject) {
if (_.isNil(items)) {
return resolve();
}
var arr = _.isArray(items) ? items : [items];
if (arr.length === 0) {
return resolve();
}
if (_.isNil(thisQueryable)) {
return reject('The underlying data queryable cannot be empty at this context.');
}
if ((mapping.parentModel !== thisQueryable.model.name) || (mapping.associationType!=='association')) {
return resolve();
}
thisArg.getChildModel().migrate(function(err) {
if (err) { return reject(err); }
var parentField = thisQueryable.model.field(mapping.parentField);
if (_.isNil(parentField)) {
return reject('The specified field cannot be found on parent model');
}
var keyField = parentField.property || parentField.name;
var parentFieldType = thisQueryable.model.context.model(parentField.type);
var values = _.intersection(_.map(_.filter(arr, function(x) {
return hasOwnProperty(x, keyField);
}), function (x) { return x[keyField];})).map(function(x) {
if (isObjectDeep(x)) {
if (parentFieldType) {
return x[parentFieldType.primaryKey];
}
throw new Error('The parent item is an object but its type cannot determined.');
}
return x;
}).filter(function(x) {
return x != null;
});
if (values.length===0) {
return resolve();
}
//search for view named summary
thisArg.getChildModel().filter(mapping.options, function(err, q) {
if (err) {
return reject(err);
}
var childField = thisArg.getChildModel().field(mapping.childField);
if (_.isNil(childField)) {
return reject('The specified field cannot be found on child model');
}
var foreignKeyField = childField.property || childField.name;
//Important Backward compatibility issue (<1.8.0)
//Description: if $levels parameter is not defined then set the default value to 0.
if (typeof q.$levels === 'undefined') {
q.$levels = 0;
}
q.prepare();
if (values.length===1) {
q.where(mapping.childField).equal(values[0]);
}
else {
q.where(mapping.childField).in(values);
}
if (q.query.hasFields() === false) {
q.select();
}
//inherit silent mode
if (thisQueryable.$silent) {
q.silent();
}
// if query is a select statement
if (q.query.$fixed == null) {
// check if foreign key field exists in query
var selectEntity = q.model.viewAdapter;
if (Object.prototype.hasOwnProperty.call(q.query.$select, selectEntity)) {
/**
* @type {Array}
*/
var select = Object.getOwnPropertyDescriptor(q.query.$select, selectEntity).value;
// find foreign key key
var find = containsField(select, foreignKeyField);
// if foreign key field does not exist
if (find == null) {
// clone query
var q1 = q.clone().select(foreignKeyField);
// and select foreign key field
var select1 = Object.getOwnPropertyDescriptor(q1.query.$select, selectEntity).value;
if (Array.isArray(select1)) {
// append field to select fields
select.push.apply(select, select1);
}
if (Array.isArray(q.query.$group)) {
find = containsField(q.query.$group, foreignKeyField);
if (find == null) {
q.query.$group.push.apply(q.query.$group, select1);
}
}
}
}
}
//final execute query
return q.getItems().then(function(childs) {
// get referrer field of parent model
var refersTo = thisArg.getParentModel().getAttribute(mapping.refersTo);
_.forEach(arr, function(x) {
var items = _.filter(childs, function(y) {
if (!_.isNil(y[foreignKeyField]) && hasOwnProperty(y[foreignKeyField], keyField)) {
return y[foreignKeyField][keyField] === x[keyField];
}
return y[foreignKeyField] === x[keyField];
});
// if parent field multiplicity attribute defines an one-to-one association
if (refersTo && (refersTo.multiplicity === 'ZeroOrOne' || refersTo.multiplicity === 'One')) {
if (items[0] != null) {
// todo raise error if there are more than one items
// get only the first item
x[mapping.refersTo] = items[0];
}
else {
// or nothing
x[mapping.refersTo] = null;
}
}
else {
// otherwise get all items
x[mapping.refersTo] = items;
}
});
return resolve();
}).catch(function(err) {
return reject(err);
});
});
});
});
}
}
class DataMappingOptimizedExtender extends DataMappingExtender {
constructor(mapping) {
super(mapping);
}
/**
* @param {*} items
* @returns {Promise|*}
*/
getParents(items) {
var thisArg = this;
var thisQueryable = this.queryable;
var mapping = this.mapping;
return new Promise(function(resolve, reject) {
if (items == null) {
return resolve();
}
var arr = Array.isArray(items) ? items : [ items ];
if (arr.length === 0) {
return resolve();
}
if (_.isNil(thisQueryable)) {
return reject('The underlying data queryable cannot be empty at this context.');
}
if ((mapping.childModel !== thisQueryable.model.name) || (mapping.associationType!=='junction')) {
return resolve();
}
var HasParentJunction = require('./has-parent-junction').HasParentJunction;
var junction = new HasParentJunction(thisQueryable.model.convert({ }), mapping);
return junction.migrate(function(err) {
if (err) {
return reject(err);
}
var parentModel = thisArg.getParentModel();
parentModel.filter(mapping.options, function(err, q) {
if (err) {
return reject(err);
}
if (!q.query.hasFields()) {
q.select();
}
//get junction sub-query
var junctionQuery = QueryUtils.query(junction.getBaseModel().name).select([mapping.associationObjectField, mapping.associationValueField])
.join(thisQueryable.query.as('j0'))
.with(QueryUtils.where(new QueryEntity(junction.getBaseModel().name).select(mapping.associationValueField))
.equal(new QueryEntity('j0').select(mapping.childField)));
//append join statement with sub-query
q.query.join(junctionQuery.as('g0'))
.with(QueryUtils.where(new QueryEntity(parentModel.viewAdapter).select(mapping.parentField))
.equal(new QueryEntity('g0').select(mapping.associationObjectField)));
if (!q.query.hasFields()) {
q.select();
}
//inherit silent mode
if (thisQueryable.$silent) {
q.silent();
}
// append child key field
if (hasOwnProperty(q.query.$select, q.model.viewAdapter)) {
const select = Object.getOwnPropertyDescriptor(q.query.$select, q.model.viewAdapter).value;
select.push(QueryField.select(mapping.associationValueField).from('g0').as('__ref'));
} else {
throw new Error('Query expression is invalid. Expected a collection of selected attributes');
}
//append child key field
return q.getItems().then(function (parents) {
_.forEach(arr, function(item) {
var values = parents.filter(function(parent) {
if (parent.__ref === item[mapping.childField]) {
return true;
}
return false;
});
var cloned = _.cloneDeep(values);
cloned.forEach(function(item1) {
delete item1.__ref;
});
item[mapping.refersTo] = cloned;
});
return resolve();
}).catch(function (err) {
return reject(err);
});
});
});
});
}
/**
* @param {*} items
* @returns {Promise|*}
*/
getChildren(items) {
var thisArg = this;
var thisQueryable = this.queryable;
var mapping = this.mapping;
return new Promise(function(resolve, reject) {
if (items == null) {
return resolve();
}
var arr = Array.isArray(items) ? items : [ items ];
if (arr.length === 0) {
return resolve();
}
if (thisQueryable == null) {
return reject('The underlying data queryable cannot be empty at this context.');
}
if ((mapping.parentModel !== thisQueryable.model.name) || (mapping.associationType!=='junction')) {
return resolve();
}
var junction;
if (mapping.childModel == null) {
var DataObjectTag = require('./data-object-tag').DataObjectTag;
junction = new DataObjectTag(thisQueryable.model.convert({ }), mapping);
return junction.migrate(function(err) {
if (err) {
return reject(err);
}
//get junction sub-query
var q = junction.getBaseModel()
.select(mapping.associationObjectField, mapping.associationValueField);
q.query.join(thisQueryable.query.as('j0'))
.with(QueryUtils.where(new QueryEntity(junction.getBaseModel().name).select(mapping.associationObjectField))
.equal(new QueryEntity('j0').select(mapping.parentField)));
if (thisQueryable.$silent) {
q.silent();
}
return q.getItems().then(function (children) {
arr.forEach(function(item) {
var values = children.filter(function(child) {
if (child[mapping.associationObjectField] === item[mapping.parentField]) {
return true;
}
return false;
});
var cloned = _.cloneDeep(values);
item[mapping.refersTo] = cloned.map(function(item) {
return item[mapping.associationValueField];
});
});
return resolve();
}).catch(function (err) {
return reject(err);
});
});
}
var DataObjectJunction = require('./data-object-junction').DataObjectJunction;
junction = new DataObjectJunction(thisQueryable.model.convert({ }), mapping);
return junction.migrate(function(err) {
if (err) {
return reject(err);
}
var childModel = thisArg.getChildModel();
childModel.filter(mapping.options, function(err, q) {
if (err) {
return reject(err);
}
if (!q.query.hasFields()) {
q.select();
}
//get junction sub-query
var junctionQuery = QueryUtils.query(junction.getBaseModel().name).select([mapping.associationObjectField, mapping.associationValueField])
.join(thisQueryable.query.as('j0'))
.with(QueryUtils.where(new QueryEntity(junction.getBaseModel().name).select(mapping.associationObjectField))
.equal(new QueryEntity('j0').select(mapping.parentField)));
//append join statement with sub-query
q.query.join(junctionQuery.as('g0'))
.with(QueryUtils.where(new QueryEntity(childModel.viewAdapter).select(mapping.childField))
.equal(new QueryEntity('g0').select(mapping.associationValueField)));
//inherit silent mode
if (thisQueryable.$silent) {
q.silent();
}
// append item reference
if (hasOwnProperty(q.query.$select, q.model.viewAdapter)) {
const select = Object.getOwnPropertyDescriptor(q.query.$select, q.model.viewAdapter).value;
select.push(QueryField.select(mapping.associationObjectField).from('g0').as('__ref'));
} else {
throw new Error('Query expression is invalid. Expected a collection of selected attributes');
}
return q.getItems().then(function (children) {
arr.forEach(function(item) {
var values = children.filter(function(child) {
// important:: use type equal operator
if (child.__ref === item[mapping.parentField]) {
return true;
}
return false;
});
var cloned = _.cloneDeep(values);
cloned.forEach(function(item1) {
delete item1.__ref;
});
item[mapping.refersTo] = cloned;
});
return resolve();
}).catch(function (err) {
return reject(err);
});
});
});
});
}
/**
* @param {*} items
* @returns {Promise|*}
*/
getAssociatedParents(items) {
var thisArg = this;
var thisQueryable = this.queryable;
var mapping = this.mapping;
return new Promise(function(resolve, reject) {
if (items == null) {
return resolve();
}
var arr = Array.isArray(items) ? items : [items];
if (arr.length === 0) {
return resolve();
}
if (thisQueryable == null) {
return reject('The underlying data queryable cannot be empty at this context.');
}
if ((mapping.childModel !== thisQueryable.model.name) || (mapping.associationType!=='association')) {
return resolve();
}
thisArg.getParentModel().migrate(function(err) {
if (err) {
return reject(err);
}
thisArg.getParentModel().filter(mapping.options, function(err, q) {
if (err) {
return reject(err);
}
//Important Backward compatibility issue (<1.8.0)
//Description: if $levels parameter is not defined then set the default value to 0.
if (q.$levels == null) {
q.$levels = 0;
}
if (q.query.$select == null) {
q.select();
}
var childField = thisQueryable.model.field(mapping.childField);
var keyField = childField.property || childField.name;
// if query is a select statement
if (thisQueryable.query.$fixed == null) {
// check if foreign key field exists in query
var selectEntity = thisQueryable.model.viewAdapter;
if (Object.prototype.hasOwnProperty.call(thisQueryable.query.$select, selectEntity)) {
/**
* @type {Array}
*/
var select = Object.getOwnPropertyDescriptor(thisQueryable.query.$select, selectEntity).value;
// find foreign key key
var find = containsField(select, keyField);
// if foreign key field does not exist
if (find == null) {
// clone query
var q1 = thisQueryable.clone().select(keyField);
// and select foreign key field
var select1 = Object.getOwnPropertyDescriptor(q1.query.$select, selectEntity).value;
if (Array.isArray(select1)) {
// append field to select fields
select.push.apply(select, select1);
}
}
}
}
q.query
.join(thisQueryable.query.as('j0'))
.with(QueryUtils.where(new QueryEntity(thisArg.getParentModel().viewAdapter).select(mapping.parentField))
.equal(new QueryEntity('j0').select(mapping.childField)));
//inherit silent mode
if (thisQueryable.$silent) {
q.silent();
}
var refersTo = thisArg.getChildModel().getAttribute(mapping.childField);
if (refersTo.nested === true) {
q.silent();
}
// validate nested attribute
q.getAllItems().then(function(results) {
var iterator = function(item) {
var find = results.find(function(result) {
return result[mapping.parentField] == item[keyField];
});
item[keyField] = _.cloneDeep(find);
};
arr.forEach(iterator);
return resolve();
}).catch(function (err) {
return reject(err);
});
});
});
});
}
/**
* @param {*} items
* @returns {Promise|*}
*/
getAssociatedChildren(items) {
var thisArg = this;
var thisQueryable = this.queryable;
var mapping = this.mapping;
return new Promise(function(resolve, reject) {
if (items == null) {
return resolve();
}
var arr = Array.isArray(items) ? items : [items];
if (arr.length === 0) {
return resolve();
}
if (thisQueryable == null) {
return reject('The underlying data queryable cannot be empty at this context.');
}
if ((mapping.parentModel !== thisQueryable.model.name) || (mapping.associationType!=='association')) {
return resolve();
}
thisArg.getChildModel().migrate(function(err) {
if (err) {
return reject(err);
}
var parentField = thisArg.getParentModel().field(mapping.parentField);
if (parentField == null) {
return reject('The specified field cannot be found on parent model');
}
var keyField = parentField.property || parentField.name;
var parentFieldType = thisQueryable.model.context.model(parentField.type);
var values = _.intersection(_.map(_.filter(arr, function(x) {
return hasOwnProperty(x, keyField);
}), function (x) {
return x[keyField];
})).map(function(x) {
if (isObjectDeep(x)) {
if (parentFieldType) {
return x[parentFieldType.primaryKey];
}
throw new Error('The parent item is an object but its type cannot determined.');
}
return x;
}).filter(function(x) {
return x != null;
});
if (values.length===0) {
return resolve();
}
//search for view named summary
thisArg.getChildModel().filter(mapping.options, function(err, q) {
if (err) {
return reject(err);
}
var childField = thisArg.getChildModel().field(mapping.childField);
if (childField == null) {
return reject('The specified field cannot be found on child model');
}
var foreignKeyField = childField.property || childField.name;
//Important Backward compatibility issue (<1.8.0)
//Description: if $levels parameter is not defined then set the default value to 0.
if (q.$levels == null) {
q.$levels = 0;
}
if (q.query.hasFields() === false) {
q.select();
}
//inherit silent mode
if (thisQueryable.$silent) {
q.silent();
}
// if query is a select statement
if (q.query.$fixed == null) {
// check if foreign key field exists in query
var selectEntity = q.model.viewAdapter;
if (Object.prototype.hasOwnProperty.call(q.query.$select, selectEntity)) {
/**
* @type {Array}
*/
var select = Object.getOwnPropertyDescriptor(q.query.$select, selectEntity).value;
// find foreign key key
var find = containsField(select, foreignKeyField);
// if foreign key field does not exist
if (find == null) {
// clone query
var q1 = q.clone().select(foreignKeyField);
// and select foreign key field
var select1 = Object.getOwnPropertyDescriptor(q1.query.$select, selectEntity).value;
if (Array.isArray(select1)) {
// append field to select fields
select.push.apply(select, select1);
}
if (Array.isArray(q.query.$group)) {
find = containsField(q.query.$group, foreignKeyField);
if (find == null) {
q.query.$group.push.apply(q.query.$group, select1);
}
}
}
}
}
// join parents
q.query.join(thisQueryable.query.as('j0'))
.with(QueryUtils.where(new QueryEntity(thisArg.getChildModel().viewAdapter).select(mapping.childField))
.equal(new QueryEntity('j0').select(mapping.parentField)));
q.prepare();
// final execute query
return q.getItems().then(function(results) {
arr.forEach(function(item) {
var children = results.filter(function(result) {
if (item[keyField] == null) {
return false;
}
var value = result[foreignKeyField];
if (value != null && hasOwnProperty(value, keyField) === true) {
// important:: use equal value operator (==)
return value[keyField] == item[keyField];
}
return value == item[keyField];
});
var refersTo = thisArg.getParentModel().getAttribute(mapping.refersTo);
// if parent field multiplicity attribute defines an one-to-one association
if (refersTo && (refersTo.multiplicity === 'ZeroOrOne' || refersTo.multiplicity === 'One')) {
if (children[0] != null) {
item[mapping.refersTo] = _.cloneDeep(children[0]);
}
else {
item[mapping.refersTo] = null;
}
}
else {
item[mapping.refersTo] = _.cloneDeep(children);
}
});
return resolve();
}).catch(function(err) {
return reject(err);
});