-
Notifications
You must be signed in to change notification settings - Fork 14
/
mobx-spine.es.js
2047 lines (1807 loc) · 77.5 KB
/
mobx-spine.es.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
import { observable, computed, action, autorun, isObservableProp, extendObservable, isObservableArray, isObservableObject, toJS } from 'mobx';
import { isArray, map, filter, find, sortBy, forIn, omit, isPlainObject, result, uniqBy, each, mapValues, get, uniqueId, uniq, mapKeys } from 'lodash';
import axios from 'axios';
import moment from 'moment';
function invariant(condition) {
var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Illegal state';
if (!condition) {
throw new Error('[mobx-spine] ' + message);
}
}
// lodash's `snakeCase` method removes dots from the string; this breaks mobx-spine
function camelToSnake(s) {
return s.replace(/([A-Z])/g, function ($1) {
return '_' + $1.toLowerCase();
});
}
// lodash's `camelCase` method removes dots from the string; this breaks mobx-spine
function snakeToCamel(s) {
if (s.startsWith('_')) {
return s;
}
return s.replace(/_\w/g, function (m) {
return m[1].toUpperCase();
});
}
// ['kind.breed', 'owner'] => { 'owner': {}, 'kind': {'breed': {}}}
function relationsToNestedKeys(relations) {
var nestedRelations = {};
relations.forEach(function (rel) {
var current = nestedRelations;
var components = rel.split('.');
var len = components.length;
for (var i = 0; i < len; ++i) {
var head = components[i];
if (current[head] === undefined) {
current[head] = {};
}
current = current[head];
}
});
return nestedRelations;
}
// Use output of relationsToNestedKeys to iterate each relation, fn is called on each model and store.
function forNestedRelations(model, nestedRelations, fn) {
Object.keys(nestedRelations).forEach(function (key) {
if (Object.keys(nestedRelations[key]).length > 0) {
if (model[key].forEach) {
model[key].forEach(function (m) {
forNestedRelations(m, nestedRelations[key], fn);
});
fn(model);
} else {
forNestedRelations(model[key], nestedRelations[key], fn);
}
}
if (model[key].forEach) {
model[key].forEach(fn);
}
fn(model[key]);
});
}
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = 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);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var defineProperty = function (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;
};
var _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _class2, _temp;
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
var AVAILABLE_CONST_OPTIONS = ['relations', 'limit', 'comparator', 'params', 'repository'];
var Store = (_class = (_temp = _class2 = function () {
createClass(Store, [{
key: 'url',
value: function url() {
// Try to auto-generate the URL.
var bname = this.constructor.backendResourceName;
if (bname) {
return '/' + bname + '/';
}
return null;
}
// The set of models has changed
// Holds the fetch parameters
}, {
key: 'initialize',
// Empty function, but can be overridden if you want to do something after initializing the model.
value: function initialize() {}
}, {
key: 'isLoading',
get: function get$$1() {
return this.__pendingRequestCount > 0;
}
}, {
key: 'length',
get: function get$$1() {
return this.models.length;
}
}, {
key: 'backendResourceName',
set: function set$$1(v) {
invariant(false, '`backendResourceName` should be a static property on the store.');
}
}]);
function Store() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, Store);
_initDefineProp(this, 'models', _descriptor, this);
_initDefineProp(this, 'params', _descriptor2, this);
_initDefineProp(this, '__pendingRequestCount', _descriptor3, this);
_initDefineProp(this, '__setChanged', _descriptor4, this);
_initDefineProp(this, '__state', _descriptor5, this);
this.__activeRelations = [];
this.Model = null;
this.api = null;
invariant(isPlainObject(options), 'Store only accepts an object with options. Chain `.parse(data)` to add models.');
forIn(options, function (value, option) {
invariant(AVAILABLE_CONST_OPTIONS.includes(option), 'Unknown option passed to store: ' + option);
});
this.__repository = options.repository;
if (options.relations) {
this.__parseRelations(options.relations);
}
if (options.limit !== undefined) {
this.setLimit(options.limit);
}
if (options.comparator) {
this.comparator = options.comparator;
}
if (options.params) {
this.params = options.params;
}
this.initialize();
}
createClass(Store, [{
key: '__parseRelations',
value: function __parseRelations(activeRelations) {
this.__activeRelations = activeRelations;
}
}, {
key: '__getApi',
value: function __getApi() {
invariant(this.api, 'You are trying to perform a API request without an `api` property defined on the store.');
invariant(result(this, 'url'), 'You are trying to perform a API request without an `url` property defined on the store.');
return this.api;
}
}, {
key: 'fromBackend',
value: function fromBackend(_ref) {
var _this = this;
var data = _ref.data,
repos = _ref.repos,
relMapping = _ref.relMapping,
reverseRelMapping = _ref.reverseRelMapping;
invariant(data, 'Backend error. Data is not set. HINT: DID YOU FORGET THE M2M again?');
this.models.replace(data.map(function (record) {
// TODO: I'm not happy at all about how this looks.
// We'll need to finetune some things, but hey, for now it works.
var model = _this._newModel();
model.fromBackend({
data: record,
repos: repos,
relMapping: relMapping,
reverseRelMapping: reverseRelMapping
});
return model;
}));
this.sort();
}
}, {
key: '_newModel',
value: function _newModel() {
var model = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
return new this.Model(model, {
store: this,
relations: this.__activeRelations
});
}
}, {
key: 'sort',
value: function sort() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
invariant(isPlainObject(options), 'Expecting a plain object for options.');
if (!this.comparator) {
return this;
}
if (typeof this.comparator === 'string') {
this.models.replace(this.sortBy(this.comparator));
} else {
this.models.replace(this.models.slice().sort(this.comparator));
}
return this;
}
}, {
key: 'parse',
value: function parse(models) {
invariant(isArray(models), 'Parameter supplied to `parse()` is not an array, got: ' + JSON.stringify(models));
// Parse does not mutate __setChanged, as it is used in
// fromBackend in the model...
this.models.replace(models.map(this._newModel.bind(this)));
this.sort();
return this;
}
}, {
key: 'parseValidationErrors',
value: function parseValidationErrors(valErrors) {
this.each(function (model) {
model.parseValidationErrors(valErrors);
});
}
}, {
key: 'clearValidationErrors',
value: function clearValidationErrors() {
this.each(function (model) {
model.clearValidationErrors();
});
}
}, {
key: 'add',
value: function add(models) {
var _this2 = this;
var singular = !isArray(models);
models = singular ? [models] : models.slice();
var modelInstances = models.map(this._newModel.bind(this));
modelInstances.forEach(function (modelInstance) {
var primaryValue = modelInstance[_this2.Model.primaryKey];
invariant(!primaryValue || !_this2.get(primaryValue), 'A model with the same primary key value "' + primaryValue + '" already exists in this store.');
_this2.__setChanged = true;
_this2.models.push(modelInstance);
});
this.sort();
return singular ? modelInstances[0] : modelInstances;
}
}, {
key: 'remove',
value: function remove(models) {
var _this3 = this;
var singular = !isArray(models);
models = singular ? [models] : models.slice();
models.forEach(function (model) {
return _this3.models.remove(model);
});
if (models.length > 0) {
this.__setChanged = true;
}
return models;
}
}, {
key: 'removeById',
value: function removeById(ids) {
var _this4 = this;
var singular = !isArray(ids);
ids = singular ? [ids] : ids.slice();
invariant(!ids.some(isNaN), 'Cannot remove a model by id that is not a number: ' + JSON.stringify(ids));
var models = ids.map(function (id) {
return _this4.get(id);
});
models.forEach(function (model) {
if (model) {
_this4.models.remove(model);
_this4.__setChanged = true;
}
});
return models;
}
}, {
key: 'clear',
value: function clear() {
var length = this.models.length;
this.models.clear();
if (length > 0) {
this.__setChanged = true;
}
}
}, {
key: 'buildFetchData',
value: function buildFetchData(options) {
return Object.assign(this.__getApi().buildFetchStoreParams(this), this.params, options.data);
}
}, {
key: 'fetch',
value: function fetch() {
var _this5 = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var data = this.buildFetchData(options);
var promise = this.wrapPendingRequestCount(this.__getApi().fetchStore({
url: options.url || result(this, 'url'),
data: data,
requestOptions: omit(options, 'data')
}).then(action(function (res) {
_this5.__state.totalRecords = res.totalRecords;
_this5.fromBackend(res);
return res.response;
})));
return promise;
}
}, {
key: '__parseNewIds',
value: function __parseNewIds(idMaps) {
this.each(function (model) {
return model.__parseNewIds(idMaps);
});
}
}, {
key: 'toJS',
value: function toJS$$1() {
return this.models.map(function (model) {
return model.toJS();
});
}
// Methods for pagination.
}, {
key: 'getPageOffset',
value: function getPageOffset() {
return (this.__state.currentPage - 1) * this.__state.limit;
}
}, {
key: 'setLimit',
value: function setLimit(limit) {
invariant(!limit || Number.isInteger(limit), 'Page limit should be a number or falsy value.');
this.__state.limit = limit || null;
}
}, {
key: 'getNextPage',
value: function getNextPage() {
invariant(this.hasNextPage, 'There is no next page.');
this.__state.currentPage += 1;
return this.fetch();
}
}, {
key: 'getPreviousPage',
value: function getPreviousPage() {
invariant(this.hasPreviousPage, 'There is no previous page.');
this.__state.currentPage -= 1;
return this.fetch();
}
}, {
key: 'setPage',
value: function setPage() {
var page = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
invariant(Number.isInteger(page) && page >= 1, 'Page should be a number above 1.');
this.__state.currentPage = page;
if (options.fetch === undefined || options.fetch) {
return this.fetch();
}
invariant(
// Always allow to go to page 1.
page <= (this.totalPages || 1), 'Page should be between 1 and ' + this.totalPages + '.');
return Promise.resolve();
}
}, {
key: 'clearSetChanges',
value: function clearSetChanges() {
this.__setChanged = false;
}
}, {
key: 'toBackendAll',
value: function toBackendAll() {
var _this6 = this;
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var relevantModels = options.onlyChanges ? this.models.filter(function (model) {
return model.isNew || model.hasUserChanges;
}) : this.models;
var modelData = relevantModels.map(function (model) {
return model.toBackendAll(options);
});
var data = [];
var relations = {};
modelData.forEach(function (model) {
data = data.concat(model.data);
forIn(model.relations, function (relModel, key) {
relations[key] = relations[key] ? relations[key].concat(relModel) : relModel;
// TODO: this primaryKey is not the primaryKey of the relation we're de-duplicating...
relations[key] = uniqBy(relations[key], _this6.Model.primaryKey);
});
});
return { data: data, relations: relations };
}
// Create a new instance of this store with a predicate applied.
// This new store will be automatically kept in-sync with all models that adhere to the predicate.
}, {
key: 'virtualStore',
value: function virtualStore(_ref2) {
var _this7 = this;
var filter$$1 = _ref2.filter,
comparator = _ref2.comparator;
var store = new this.constructor({
relations: this.__activeRelations,
comparator: comparator
});
// Oh gawd MobX is so awesome.
var events = autorun(function () {
var models = _this7.filter(filter$$1);
store.models.replace(models);
store.sort();
// When the parent store is busy, make sure the virtual store is
// also busy.
store.__pendingRequestCount = _this7.__pendingRequestCount;
});
store.unsubscribeVirtualStore = events;
return store;
}
// Helper methods to read models.
}, {
key: 'get',
value: function get$$1(id) {
// The id can be defined as a string or int, but we want it to work in both cases.
return this.models.find(function (model) {
return model[model.constructor.primaryKey] == id;
} // eslint-disable-line eqeqeq
);
}
}, {
key: 'getByIds',
value: function getByIds(ids) {
return this.models.filter(function (model) {
var id = model[model.constructor.primaryKey];
return ids.includes(id) || ids.includes('' + id);
});
}
}, {
key: 'map',
value: function map$$1(predicate) {
return map(this.models, predicate);
}
}, {
key: 'mapByPrimaryKey',
value: function mapByPrimaryKey() {
return this.map(this.Model.primaryKey);
}
}, {
key: 'filter',
value: function filter$$1(predicate) {
return filter(this.models, predicate);
}
}, {
key: 'find',
value: function find$$1(predicate) {
return find(this.models, predicate);
}
}, {
key: 'each',
value: function each$$1(predicate) {
return this.models.forEach(predicate);
}
}, {
key: 'forEach',
value: function forEach(predicate) {
return this.models.forEach(predicate);
}
}, {
key: 'sortBy',
value: function sortBy$$1(iteratees) {
return sortBy(this.models, iteratees);
}
}, {
key: 'at',
value: function at(index) {
var zeroLength = this.length - 1;
invariant(index <= zeroLength, 'Index ' + index + ' is out of bounds (max ' + zeroLength + ').');
if (index < 0) {
index += this.length;
}
return this.models[index];
}
}, {
key: 'wrapPendingRequestCount',
value: function wrapPendingRequestCount(promise) {
var _this8 = this;
this.__pendingRequestCount++;
return promise.then(function (res) {
_this8.__pendingRequestCount--;
return res;
}).catch(function (err) {
_this8.__pendingRequestCount--;
throw err;
});
}
}, {
key: 'saveAllFiles',
value: function saveAllFiles() {
var relations = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var promises = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = this.models[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var model = _step.value;
promises.push(model.saveAllFiles(relations));
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return Promise.all(promises);
}
}, {
key: 'totalPages',
get: function get$$1() {
if (!this.__state.limit) {
return 0;
}
return Math.ceil(this.__state.totalRecords / this.__state.limit);
}
}, {
key: 'currentPage',
get: function get$$1() {
return this.__state.currentPage;
}
}, {
key: 'hasNextPage',
get: function get$$1() {
return this.__state.currentPage + 1 <= this.totalPages;
}
}, {
key: 'hasPreviousPage',
get: function get$$1() {
return this.__state.currentPage > 1;
}
}, {
key: 'hasUserChanges',
get: function get$$1() {
return this.hasSetChanges || this.models.some(function (m) {
return m.hasUserChanges;
});
}
// TODO: Maybe we can keep track of what got added and what got
// removed exactly. For now this should be enough.
}, {
key: 'hasSetChanges',
get: function get$$1() {
return this.__setChanged;
}
}]);
return Store;
}(), _class2.backendResourceName = '', _temp), (_descriptor = _applyDecoratedDescriptor(_class.prototype, 'models', [observable], {
enumerable: true,
initializer: function initializer() {
return [];
}
}), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, 'params', [observable], {
enumerable: true,
initializer: function initializer() {
return {};
}
}), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, '__pendingRequestCount', [observable], {
enumerable: true,
initializer: function initializer() {
return 0;
}
}), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, '__setChanged', [observable], {
enumerable: true,
initializer: function initializer() {
return false;
}
}), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, '__state', [observable], {
enumerable: true,
initializer: function initializer() {
return {
currentPage: 1,
limit: 25,
totalRecords: 0
};
}
}), _applyDecoratedDescriptor(_class.prototype, 'isLoading', [computed], Object.getOwnPropertyDescriptor(_class.prototype, 'isLoading'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'length', [computed], Object.getOwnPropertyDescriptor(_class.prototype, 'length'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'fromBackend', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'fromBackend'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'sort', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'sort'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'parse', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'parse'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'add', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'add'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'remove', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'remove'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'removeById', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'removeById'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'clear', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'clear'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'fetch', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'fetch'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'setLimit', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'setLimit'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'totalPages', [computed], Object.getOwnPropertyDescriptor(_class.prototype, 'totalPages'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'currentPage', [computed], Object.getOwnPropertyDescriptor(_class.prototype, 'currentPage'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'hasNextPage', [computed], Object.getOwnPropertyDescriptor(_class.prototype, 'hasNextPage'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'hasPreviousPage', [computed], Object.getOwnPropertyDescriptor(_class.prototype, 'hasPreviousPage'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'getNextPage', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'getNextPage'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'getPreviousPage', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'getPreviousPage'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'setPage', [action], Object.getOwnPropertyDescriptor(_class.prototype, 'setPage'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'hasUserChanges', [computed], Object.getOwnPropertyDescriptor(_class.prototype, 'hasUserChanges'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'hasSetChanges', [computed], Object.getOwnPropertyDescriptor(_class.prototype, 'hasSetChanges'), _class.prototype)), _class);
var _class$1, _descriptor$1, _descriptor2$1, _descriptor3$1, _descriptor4$1, _descriptor5$1, _descriptor6, _descriptor7, _class2$1, _temp$1;
function _initDefineProp$1(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _applyDecoratedDescriptor$1(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function concatInDict(dict, key, value) {
dict[key] = dict[key] ? dict[key].concat(value) : value;
}
// Find the relation name before the first dot, and include all other relations after it
// Example: input `animal.kind.breed` output -> `['animal', 'kind.breed']`
var RE_SPLIT_FIRST_RELATION = /([^.]+)\.(.+)/;
// TODO: find a way to get a list of existing properties automatically.
var FORBIDDEN_ATTRS = ['url', 'urlRoot', 'api', 'isNew', 'isLoading', 'parse', 'save', 'clear'];
var Model = (_class$1 = (_temp$1 = _class2$1 = function () {
createClass(Model, [{
key: 'urlRoot',
value: function urlRoot() {
// Try to auto-generate the URL.
var bname = this.constructor.backendResourceName;
if (bname) {
return '/' + bname + '/';
}
return null;
}
// How the model is known at the backend. This is useful when the model is in a relation that has a different name.
// Holds original attributes with values, so `clear()` knows what to reset to (quite ugly).
// Holds activated - nested - relations (e.g. `['animal', 'animal.breed']`)
// Holds activated - non-nested - relations (e.g. `['animal']`)
// A `cid` can be used to identify the model locally.
// URL query params that are added to fetch requests.
// Holds fields (attrs+relations) that have been changed via setInput()
// File state
}, {
key: 'wrapPendingRequestCount',
value: function wrapPendingRequestCount(promise) {
var _this = this;
this.__pendingRequestCount++;
return promise.then(function (res) {
_this.__pendingRequestCount--;
return res;
}).catch(function (err) {
_this.__pendingRequestCount--;
throw err;
});
}
// Useful to reference to this model in a relation - that is not yet saved to the backend.
}, {
key: 'getNegativeId',
value: function getNegativeId() {
return -parseInt(this.cid.replace('m', ''));
}
}, {
key: 'getInternalId',
value: function getInternalId() {
if (this.isNew) {
return this.getNegativeId();
}
return this[this.constructor.primaryKey];
}
}, {
key: 'casts',
value: function casts() {
return {};
}
}, {
key: 'fileFields',
value: function fileFields() {
return [];
}
// Empty function, but can be overridden if you want to do something after initializing the model.
}, {
key: 'initialize',
value: function initialize() {}
}, {
key: 'url',
get: function get$$1() {
var id = this[this.constructor.primaryKey];
return '' + result(this, 'urlRoot') + (id ? id + '/' : '');
}
}, {
key: 'isNew',
get: function get$$1() {
return !this[this.constructor.primaryKey];
}
}, {
key: 'isLoading',
get: function get$$1() {
return this.__pendingRequestCount > 0;
}
}, {
key: 'primaryKey',
set: function set$$1(v) {
invariant(false, '`primaryKey` should be a static property on the model.');
}
}, {
key: 'backendResourceName',
set: function set$$1(v) {
invariant(false, '`backendResourceName` should be a static property on the model.');
}
}]);
function Model(data) {
var _this2 = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, Model);
this.__attributes = [];
this.__originalAttributes = {};
this.__activeRelations = [];
this.__activeCurrentRelations = [];
this.api = null;
this.cid = 'm' + uniqueId();
_initDefineProp$1(this, '__backendValidationErrors', _descriptor$1, this);
_initDefineProp$1(this, '__pendingRequestCount', _descriptor2$1, this);
_initDefineProp$1(this, '__fetchParams', _descriptor3$1, this);
_initDefineProp$1(this, '__changes', _descriptor4$1, this);
_initDefineProp$1(this, '__fileChanges', _descriptor5$1, this);
_initDefineProp$1(this, '__fileDeletions', _descriptor6, this);
_initDefineProp$1(this, '__fileExists', _descriptor7, this);
this.__store = options.store;
this.__repository = options.repository;
// Find all attributes. Not all observables are an attribute.
forIn(this, function (value, key) {
if (!key.startsWith('__') && isObservableProp(_this2, key)) {
invariant(!FORBIDDEN_ATTRS.includes(key), 'Forbidden attribute key used: `' + key + '`');
_this2.__attributes.push(key);
var newValue = value;
// An array or object observable can be mutated, so we want to ensure we always have
// the original not-yet-mutated object/array.
if (isObservableArray(value)) {
newValue = value.slice();
} else if (isObservableObject(value)) {
newValue = Object.assign({}, value);
}
_this2.__originalAttributes[key] = newValue;
}
});
if (options.relations) {
this.__parseRelations(options.relations);
}
if (data) {
this.parse(data);
}
this.initialize();
this.saveFile = this.saveFile.bind(this);
}
createClass(Model, [{
key: '__parseRelations',
value: function __parseRelations(activeRelations) {
var _this3 = this;
this.__activeRelations = activeRelations;
// TODO: No idea why getting the relations only works when it's a Function.
var relations = this.relations && this.relations();
var relModels = {};
activeRelations.forEach(function (aRel) {
// If aRel is null, this relation is already defined by another aRel
// IE.: town.restaurants.chef && town
if (aRel === null) {
return;
}
var relNames = aRel.match(RE_SPLIT_FIRST_RELATION);
var currentRel = relNames ? relNames[1] : aRel;
var otherRelNames = relNames && relNames[2];
var currentProp = relModels[currentRel];
var otherRels = otherRelNames && [otherRelNames];
// When two nested relations are defined next to each other (e.g. `['kind.breed', 'kind.location']`),
// the relation `kind` only needs to be initialized once.
relModels[currentRel] = currentProp ? currentProp.concat(otherRels) : otherRels;
invariant(!_this3.__attributes.includes(currentRel), 'Cannot define `' + currentRel + '` as both an attribute and a relation. You probably need to remove the attribute.');
if (!_this3.__activeCurrentRelations.includes(currentRel)) {
_this3.__activeCurrentRelations.push(currentRel);
}
});
extendObservable(this, mapValues(relModels, function (otherRelNames, relName) {
var RelModel = relations[relName];
invariant(RelModel, 'Specified relation "' + relName + '" does not exist on model.');
var options = { relations: otherRelNames };
if (RelModel.prototype instanceof Store) {
return new RelModel(options);
}
return new RelModel(null, options);
}));
}