forked from 418sec/js-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs-data.js
14041 lines (12685 loc) · 485 KB
/
js-data.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
/*!
* js-data
* @version 4.0.0-beta.4 - Homepage <http://www.js-data.io/>
* @author js-data project authors
* @copyright (c) 2014-2016 js-data project authors
* @license MIT <https://github.com/js-data/js-data/blob/master/LICENSE>
*
* @overview js-data is a framework-agnostic, datastore-agnostic ORM/ODM for Node.js and the Browser.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define('js-data', ['exports'], factory) :
(global = global || self, factory(global.JSData = {}));
}(this, (function (exports) { 'use strict';
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (isNativeReflectConstruct()) {
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class;
if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _get(target, property, receiver) {
if (typeof Reflect !== "undefined" && Reflect.get) {
_get = Reflect.get;
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
/**
* Utility methods used by JSData.
*
* @example
* import { utils } from 'js-data';
* console.log(utils.isString('foo')); // true
*
* @namespace utils
* @type {Object}
*/
var DOMAIN = 'utils';
var INFINITY = 1 / 0;
var MAX_INTEGER = 1.7976931348623157e308;
var BOOL_TAG = '[object Boolean]';
var DATE_TAG = '[object Date]';
var FUNC_TAG = '[object Function]';
var NUMBER_TAG = '[object Number]';
var OBJECT_TAG = '[object Object]';
var REGEXP_TAG = '[object RegExp]';
var STRING_TAG = '[object String]';
var objToString = Object.prototype.toString;
var PATH = /^(.+)\.(.+)$/;
var ERRORS = {
'400': function _() {
return "expected: ".concat(arguments.length <= 0 ? undefined : arguments[0], ", found: ").concat((arguments.length <= 2 ? undefined : arguments[2]) ? arguments.length <= 1 ? undefined : arguments[1] : _typeof(arguments.length <= 1 ? undefined : arguments[1]));
},
'404': function _() {
return "".concat(arguments.length <= 0 ? undefined : arguments[0], " not found");
}
};
var toInteger = function toInteger(value) {
if (!value) {
return 0;
} // Coerce to number
value = +value;
if (value === INFINITY || value === -INFINITY) {
var sign = value < 0 ? -1 : 1;
return sign * MAX_INTEGER;
}
var remainder = value % 1;
return value === value ? remainder ? value - remainder : value : 0; // eslint-disable-line
};
var toStr = function toStr(value) {
return objToString.call(value);
};
var isPlainObject = function isPlainObject(value) {
return !!value && _typeof(value) === 'object' && value.constructor === Object;
};
var mkdirP = function mkdirP(object, path) {
if (!path) {
return object;
}
var parts = path.split('.');
parts.forEach(function (key) {
if (!object[key]) {
object[key] = {};
}
object = object[key];
});
return object;
};
var utils = {
/**
* Shallow copy properties that meet the following criteria from `src` to
* `dest`:
*
* - own enumerable
* - not a function
* - does not start with "_"
*
* @method utils._
* @param {object} dest Destination object.
* @param {object} src Source object.
* @private
* @since 3.0.0
*/
_: function _(dest, src) {
utils.forOwn(src, function (value, key) {
if (key && dest[key] === undefined && !utils.isFunction(value) && key.indexOf('_') !== 0) {
dest[key] = value;
}
});
},
/**
* Recursively iterates over relations found in `opts.with`.
*
* @method utils._forRelation
* @param {object} opts Configuration options.
* @param {Relation} def Relation definition.
* @param {Function} fn Callback function.
* @param {*} [thisArg] Execution context for the callback function.
* @private
* @since 3.0.0
*/
_forRelation: function _forRelation() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var def = arguments.length > 1 ? arguments[1] : undefined;
var fn = arguments.length > 2 ? arguments[2] : undefined;
var thisArg = arguments.length > 3 ? arguments[3] : undefined;
var relationName = def.relation;
var containedName = null;
var index;
opts["with"] = opts["with"] || [];
if ((index = utils._getIndex(opts["with"], relationName)) >= 0) {
containedName = relationName;
} else if ((index = utils._getIndex(opts["with"], def.localField)) >= 0) {
containedName = def.localField;
}
if (opts.withAll) {
fn.call(thisArg, def, {});
return;
} else if (!containedName) {
return;
}
var optsCopy = {};
utils.fillIn(optsCopy, def.getRelation());
utils.fillIn(optsCopy, opts);
optsCopy["with"] = opts["with"].slice();
optsCopy._activeWith = optsCopy["with"].splice(index, 1)[0];
optsCopy["with"].forEach(function (relation, i) {
if (relation && relation.indexOf(containedName) === 0 && relation.length >= containedName.length && relation[containedName.length] === '.') {
optsCopy["with"][i] = relation.substr(containedName.length + 1);
} else {
optsCopy["with"][i] = '';
}
});
fn.call(thisArg, def, optsCopy);
},
/**
* Find the index of a relation in the given list
*
* @method utils._getIndex
* @param {string[]} list List to search.
* @param {string} relation Relation to find.
* @private
* @returns {number}
*/
_getIndex: function _getIndex(list, relation) {
var index = -1;
list.forEach(function (_relation, i) {
if (_relation === relation) {
index = i;
return false;
} else if (utils.isObject(_relation)) {
if (_relation.relation === relation) {
index = i;
return false;
}
}
});
return index;
},
/**
* Define hidden (non-enumerable), writable properties on `target` from the
* provided `props`.
*
* @example
* import { utils } from 'js-data';
* function Cat () {}
* utils.addHiddenPropsToTarget(Cat.prototype, {
* say () {
* console.log('meow');
* }
* });
* const cat = new Cat();
* cat.say(); // "meow"
*
* @method utils.addHiddenPropsToTarget
* @param {object} target That to which `props` should be added.
* @param {object} props Properties to be added to `target`.
* @since 3.0.0
*/
addHiddenPropsToTarget: function addHiddenPropsToTarget(target, props) {
var map = {};
Object.keys(props).forEach(function (propName) {
var descriptor = Object.getOwnPropertyDescriptor(props, propName);
descriptor.enumerable = false;
map[propName] = descriptor;
});
Object.defineProperties(target, map);
},
/**
* Return whether the two objects are deeply different.
*
* @example
* import { utils } from 'js-data';
* utils.areDifferent({}, {}); // false
* utils.areDifferent({ a: 1 }, { a: 1 }); // false
* utils.areDifferent({ foo: 'bar' }, {}); // true
*
* @method utils.areDifferent
* @param newObject
* @param oldObject
* @param {object} [opts] Configuration options.
* @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.
* @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.
* @returns {boolean} Whether the two objects are deeply different.
* @see utils.diffObjects
* @since 3.0.0
*/
areDifferent: function areDifferent(newObject, oldObject) {
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var diff = utils.diffObjects(newObject, oldObject, opts);
var diffCount = Object.keys(diff.added).length + Object.keys(diff.removed).length + Object.keys(diff.changed).length;
return diffCount > 0;
},
/**
* Deep copy a value.
*
* @example
* import { utils } from 'js-data';
* const a = { foo: { bar: 'baz' } };
* const b = utils.copy(a);
* a === b; // false
* utils.areDifferent(a, b); // false
*
* @param {*} from Value to deep copy.
* @param {*} [to] Destination object for the copy operation.
* @param {*} [stackFrom] For internal use.
* @param {*} [stackTo] For internal use.
* @param {string[]|RegExp[]} [blacklist] List of strings or RegExp of
* properties to skip.
* @param {boolean} [plain] Whether to make a plain copy (don't try to use
* original prototype).
* @returns {*} Deep copy of `from`.
* @since 3.0.0
*/
copy: function copy(from, to, stackFrom, stackTo, blacklist, plain) {
if (!to) {
to = from;
if (from) {
if (utils.isArray(from)) {
to = utils.copy(from, [], stackFrom, stackTo, blacklist, plain);
} else if (utils.isDate(from)) {
to = new Date(from.getTime());
} else if (utils.isRegExp(from)) {
to = new RegExp(from.source, from.toString().match(/[^/]*$/)[0]);
to.lastIndex = from.lastIndex;
} else if (utils.isObject(from)) {
if (plain) {
to = utils.copy(from, {}, stackFrom, stackTo, blacklist, plain);
} else {
to = utils.copy(from, Object.create(Object.getPrototypeOf(from)), stackFrom, stackTo, blacklist, plain);
}
}
}
} else {
if (from === to) {
throw utils.err("".concat(DOMAIN, ".copy"))(500, 'Cannot copy! Source and destination are identical.');
}
stackFrom = stackFrom || [];
stackTo = stackTo || [];
if (utils.isObject(from)) {
var index = stackFrom.indexOf(from);
if (index !== -1) {
return stackTo[index];
}
stackFrom.push(from);
stackTo.push(to);
}
var result;
if (utils.isArray(from)) {
var i;
to.length = 0;
for (i = 0; i < from.length; i++) {
result = utils.copy(from[i], null, stackFrom, stackTo, blacklist, plain);
if (utils.isObject(from[i])) {
stackFrom.push(from[i]);
stackTo.push(result);
}
to.push(result);
}
} else {
if (utils.isArray(to)) {
to.length = 0;
} else {
utils.forOwn(to, function (value, key) {
delete to[key];
});
}
for (var key in from) {
if (from.hasOwnProperty(key)) {
if (utils.isBlacklisted(key, blacklist)) {
continue;
}
result = utils.copy(from[key], null, stackFrom, stackTo, blacklist, plain);
if (utils.isObject(from[key])) {
stackFrom.push(from[key]);
stackTo.push(result);
}
to[key] = result;
}
}
}
}
return to;
},
/**
* Recursively shallow fill in own enumerable properties from `source` to
* `dest`.
*
* @example
* import { utils } from 'js-data';
* const a = { foo: { bar: 'baz' }, beep: 'boop' };
* const b = { beep: 'bip' };
* utils.deepFillIn(b, a);
* console.log(b); // {"foo":{"bar":"baz"},"beep":"bip"}
*
* @method utils.deepFillIn
* @param {object} dest The destination object.
* @param {object} source The source object.
* @see utils.fillIn
* @see utils.deepMixIn
* @since 3.0.0
*/
deepFillIn: function deepFillIn(dest, source) {
if (source) {
utils.forOwn(source, function (value, key) {
var existing = dest[key];
if (isPlainObject(value) && isPlainObject(existing)) {
utils.deepFillIn(existing, value);
} else if (!dest.hasOwnProperty(key) || dest[key] === undefined) {
dest[key] = value;
}
});
}
return dest;
},
/**
* Recursively shallow copy enumerable properties from `source` to `dest`.
*
* @example
* import { utils } from 'js-data';
* const a = { foo: { bar: 'baz' }, beep: 'boop' };
* const b = { beep: 'bip' };
* utils.deepFillIn(b, a);
* console.log(b); // {"foo":{"bar":"baz"},"beep":"boop"}
*
* @method utils.deepMixIn
* @param {object} dest The destination object.
* @param {object} source The source object.
* @see utils.fillIn
* @see utils.deepFillIn
* @since 3.0.0
*/
deepMixIn: function deepMixIn(dest, source) {
if (source) {
// tslint:disable-next-line:forin
for (var key in source) {
var value = source[key];
var existing = dest[key];
if (isPlainObject(value) && isPlainObject(existing)) {
utils.deepMixIn(existing, value);
} else {
dest[key] = value;
}
}
}
return dest;
},
/**
* Return a diff of the base object to the comparison object.
*
* @example
* import { utils } from 'js-data';
* const oldObject = { foo: 'bar', a: 1234 };
* const newObject = { beep: 'boop', a: 5678 };
* const diff = utils.diffObjects(oldObject, newObject);
* console.log(diff.added); // {"beep":"boop"}
* console.log(diff.changed); // {"a":5678}
* console.log(diff.removed); // {"foo":undefined}
*
* @method utils.diffObjects
* @param {object} newObject Comparison object.
* @param {object} oldObject Base object.
* @param {object} [opts] Configuration options.
* @param {Function} [opts.equalsFn={@link utils.deepEqual}] Equality function.
* @param {array} [opts.ignore=[]] Array of strings or RegExp of fields to ignore.
* @returns {Object} The diff from the base object to the comparison object.
* @see utils.areDifferent
* @since 3.0.0
*/
diffObjects: function diffObjects(newObject, oldObject) {
var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var equalsFn = opts.equalsFn;
var blacklist = opts.ignore;
var diff = {
added: {},
changed: {},
removed: {}
};
if (!utils.isFunction(equalsFn)) {
equalsFn = utils.deepEqual;
}
var newKeys = Object.keys(newObject).filter(function (key) {
return !utils.isBlacklisted(key, blacklist);
});
var oldKeys = Object.keys(oldObject).filter(function (key) {
return !utils.isBlacklisted(key, blacklist);
}); // Check for properties that were added or changed
newKeys.forEach(function (key) {
var oldValue = oldObject[key];
var newValue = newObject[key];
if (equalsFn(oldValue, newValue)) {
return;
}
if (oldValue === undefined) {
diff.added[key] = newValue;
} else {
diff.changed[key] = newValue;
}
}); // Check for properties that were removed
oldKeys.forEach(function (key) {
var oldValue = oldObject[key];
var newValue = newObject[key];
if (newValue === undefined && oldValue !== undefined) {
diff.removed[key] = undefined;
}
});
return diff;
},
/**
* Return whether the two values are equal according to the `==` operator.
*
* @example
* import { utils } from 'js-data';
* console.log(utils.equal(1,1)); // true
* console.log(utils.equal(1,'1')); // true
* console.log(utils.equal(93, 66)); // false
*
* @method utils.equal
* @param {*} a First value in the comparison.
* @param {*} b Second value in the comparison.
* @returns {boolean} Whether the two values are equal according to `==`.
* @since 3.0.0
*/
equal: function equal(a, b) {
// tslint:disable-next-line:triple-equals
return a == b; // eslint-disable-line
},
/**
* Produce a factory function for making Error objects with the provided
* metadata. Used throughout the various js-data components.
*
* @example
* import { utils } from 'js-data';
* const errorFactory = utils.err('domain', 'target');
* const error400 = errorFactory(400, 'expected type', 'actual type');
* console.log(error400); // [Error: [domain:target] expected: expected type, found: string
* http://www.js-data.io/v3.0/docs/errors#400]
* @method utils.err
* @param {string} domain Namespace.
* @param {string} target Target.
* @returns {Function} Factory function.
* @since 3.0.0
*/
err: function err(domain, target) {
return function (code) {
var prefix = "[".concat(domain, ":").concat(target, "] ");
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var message = ERRORS[code].apply(null, args);
message = "".concat(prefix).concat(message, "\nhttp://www.js-data.io/v3.0/docs/errors#").concat(code);
return new Error(message);
};
},
/**
* Add eventing capabilities into the target object.
*
* @example
* import { utils } from 'js-data';
* const user = { name: 'John' };
* utils.eventify(user);
* user.on('foo', () => console.log(arguments));
* user.emit('foo', 1, 'bar'); // should log to console values (1, "bar")
*
* @method utils.eventify
* @param {object} target Target object.
* @param {Function} [getter] Custom getter for retrieving the object's event
* listeners.
* @param {Function} [setter] Custom setter for setting the object's event
* listeners.
* @since 3.0.0
*/
eventify: function eventify(target, getter, setter) {
target = target || this;
var _events = {};
if (!getter && !setter) {
getter = function getter() {
return _events;
};
setter = function setter(value) {
return _events = value;
};
}
Object.defineProperties(target, {
emit: {
value: function value() {
var events = getter.call(this) || {};
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
var type = args.shift();
var listeners = events[type] || [];
var i;
for (i = 0; i < listeners.length; i++) {
listeners[i].f.apply(listeners[i].c, args);
}
listeners = events.all || [];
args.unshift(type);
for (i = 0; i < listeners.length; i++) {
listeners[i].f.apply(listeners[i].c, args);
}
}
},
off: {
value: function value(type, func) {
var events = getter.call(this);
var listeners = events[type];
if (!listeners) {
setter.call(this, {});
} else if (func) {
for (var i = 0; i < listeners.length; i++) {
if (listeners[i].f === func) {
listeners.splice(i, 1);
break;
}
}
} else {
listeners.splice(0, listeners.length);
}
}
},
on: {
value: function value(type, func, thisArg) {
if (!getter.call(this)) {
setter.call(this, {});
}
var events = getter.call(this);
events[type] = events[type] || [];
events[type].push({
c: thisArg,
f: func
});
}
}
});
},
/**
* Shallow copy own enumerable properties from `src` to `dest` that are on
* `src` but are missing from `dest.
*
* @example
* import { utils } from 'js-data';
* const a = { foo: 'bar', beep: 'boop' };
* const b = { beep: 'bip' };
* utils.fillIn(b, a);
* console.log(b); // {"foo":"bar","beep":"bip"}
*
* @method utils.fillIn
* @param {object} dest The destination object.
* @param src
* @see utils.deepFillIn
* @see utils.deepMixIn
* @since 3.0.0
*/
fillIn: function fillIn(dest, src) {
utils.forOwn(src, function (value, key) {
if (!dest.hasOwnProperty(key) || dest[key] === undefined) {
dest[key] = value;
}
});
},
/**
* Find the last index of an item in an array according to the given checker function.
*
* @example
* import { utils } from 'js-data';
*
* const john = { name: 'John', age: 20 };
* const sara = { name: 'Sara', age: 25 };
* const dan = { name: 'Dan', age: 20 };
* const users = [john, sara, dan];
*
* console.log(utils.findIndex(users, (user) => user.age === 25)); // 1
* console.log(utils.findIndex(users, (user) => user.age > 19)); // 2
* console.log(utils.findIndex(users, (user) => user.name === 'John')); // 0
* console.log(utils.findIndex(users, (user) => user.name === 'Jimmy')); // -1
*
* @method utils.findIndex
* @param {array} array The array to search.
* @param {Function} fn Checker function.
* @returns {number} Index if found or -1 if not found.
* @since 3.0.0
*/
findIndex: function findIndex(array, fn) {
var index = -1;
if (!array) {
return index;
}
array.forEach(function (record, i) {
if (fn(record)) {
index = i;
return false;
}
});
return index;
},
/**
* Recursively iterate over a {@link Mapper}'s relations according to
* `opts.with`.
*
* @method utils.forEachRelation
* @param {Mapper} mapper Mapper.
* @param {object} opts Configuration options.
* @param {Function} fn Callback function.
* @param {*} thisArg Execution context for the callback function.
* @since 3.0.0
*/
forEachRelation: function forEachRelation(mapper, opts, fn, thisArg) {
var relationList = mapper.relationList || [];
if (!relationList.length) {
return;
}
relationList.forEach(function (def) {
utils._forRelation(opts, def, fn, thisArg);
});
},
/**
* Iterate over an object's own enumerable properties.
*
* @example
* import { utils } from 'js-data';
* const a = { b: 1, c: 4 };
* let sum = 0;
* utils.forOwn(a, function (value, key) {
* sum += value;
* });
* console.log(sum); // 5
*
* @method utils.forOwn
* @param obj
* @param {Function} fn Iteration function.
* @param {object} [thisArg] Content to which to bind `fn`.
* @since 3.0.0
*/
forOwn: function forOwn(obj, fn, thisArg) {
var keys = Object.keys(obj);
var len = keys.length;
var i;
for (i = 0; i < len; i++) {
if (fn.call(thisArg, obj[keys[i]], keys[i], obj) === false) {
break;
}
}
},
/**
* Proxy for `JSON.parse`.
*
* @example
* import { utils } from 'js-data';
*
* const a = utils.fromJson('{"name" : "John"}');
* console.log(a); // { name: 'John' }
*
* @method utils.fromJson
* @param {string} json JSON to parse.
* @returns {Object} Parsed object.
* @see utils.toJson
* @since 3.0.0
*/
fromJson: function fromJson(json) {
return utils.isString(json) ? JSON.parse(json) : json;
},
/**
* Retrieve the specified property from the given object. Supports retrieving
* nested properties.
*
* @example
* import { utils } from 'js-data';
* const a = { foo: { bar: 'baz' }, beep: 'boop' };
* console.log(utils.get(a, 'beep')); // "boop"
* console.log(utils.get(a, 'foo.bar')); // "baz"
*
* @method utils.get
* @param {object} object Object from which to retrieve a property's value.
* @param {string} prop Property to retrieve.
* @returns {*} Value of the specified property.
* @see utils.set
* @since 3.0.0
*/
get: function get(object, prop) {