-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
internal-model.js
1228 lines (1009 loc) · 32.1 KB
/
internal-model.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 Ember from 'ember';
import { DEBUG } from '@glimmer/env';
import { assert } from '@ember/debug';
import RootState from "./states";
import Relationships from "../relationships/state/create";
import Snapshot from "../snapshot";
import isEnabled from '../../features';
import OrderedSet from "../ordered-set";
import { getOwner } from '../../utils';
import {
RecordReference,
BelongsToReference,
HasManyReference
} from "../references";
const {
get,
set,
copy,
Error: EmberError,
inspect,
isEmpty,
isEqual,
setOwner,
RSVP,
RSVP: { Promise }
} = Ember;
const assign = Ember.assign || Ember.merge;
/*
The TransitionChainMap caches the `state.enters`, `state.setups`, and final state reached
when transitioning from one state to another, so that future transitions can replay the
transition without needing to walk the state tree, collect these hook calls and determine
the state to transition into.
A future optimization would be to build a single chained method out of the collected enters
and setups. It may also be faster to do a two level cache (from: { to }) instead of caching based
on a key that adds the two together.
*/
const TransitionChainMap = Object.create(null);
const _extractPivotNameCache = Object.create(null);
const _splitOnDotCache = Object.create(null);
function splitOnDot(name) {
return _splitOnDotCache[name] || (
_splitOnDotCache[name] = name.split('.')
);
}
function extractPivotName(name) {
return _extractPivotNameCache[name] || (
_extractPivotNameCache[name] = splitOnDot(name)[0]
);
}
function areAllModelsUnloaded(internalModels) {
for (let i=0; i<internalModels.length; ++i) {
let record = internalModels[i]._record;
if (record && !(record.get('isDestroyed') || record.get('isDestroying'))) {
return false;
}
}
return true;
}
// this (and all heimdall instrumentation) will be stripped by a babel transform
// https://github.com/heimdalljs/babel5-plugin-strip-heimdall
const {
_triggerDeferredTriggers,
changedAttributes,
createSnapshot,
flushChangedAttributes,
hasChangedAttributes,
materializeRecord,
new_InternalModel,
send,
setupData,
transitionTo,
updateChangedAttributes
} = heimdall.registerMonitor('InternalModel',
'_triggerDeferredTriggers',
'changedAttributes',
'createSnapshot',
'flushChangedAttributes',
'hasChangedAttributes',
'materializeRecord',
'new_InternalModel',
'send',
'setupData',
'transitionTo',
'updateChangedAttributes'
);
let InternalModelReferenceId = 1;
let nextBfsId = 1;
/*
`InternalModel` is the Model class that we use internally inside Ember Data to represent models.
Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class.
We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as
a performance optimization.
`InternalModel` should never be exposed to application code. At the boundaries of the system, in places
like `find`, `push`, etc. we convert between Models and InternalModels.
We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model`
if they are needed.
@private
@class InternalModel
*/
export default class InternalModel {
constructor(modelName, id, store, data) {
heimdall.increment(new_InternalModel);
this.id = id;
// this ensure ordered set can quickly identify this as unique
this[Ember.GUID_KEY] = InternalModelReferenceId++ + 'internal-model';
this.store = store;
this.modelName = modelName;
this._loadingPromise = null;
this._record = null;
this._isDestroyed = false;
this.isError = false;
this._isUpdatingRecordArrays = false; // used by the recordArrayManager
// During dematerialization we don't want to rematerialize the record. The
// reason this might happen is that dematerialization removes records from
// record arrays, and Ember arrays will always `objectAt(0)` and
// `objectAt(len - 1)` to test whether or not `firstObject` or `lastObject`
// have changed.
this._isDematerializing = false;
this.resetRecord();
if (data) {
this.__data = data;
}
// caches for lazy getters
this._modelClass = null;
this.__deferredTriggers = null;
this.__recordArrays = null;
this._references = null;
this._recordReference = null;
this.__relationships = null;
this.__implicitRelationships = null;
// Used during the mark phase of unloading to avoid checking the same internal
// model twice in the same scan
this._bfsId = 0;
}
get modelClass() {
return this._modelClass || (this._modelClass = this.store._modelFor(this.modelName));
}
get type() {
return this.modelClass;
}
get recordReference() {
if (this._recordReference === null) {
this._recordReference = new RecordReference(this.store, this);
}
return this._recordReference;
}
get _recordArrays() {
if (this.__recordArrays === null) {
this.__recordArrays = OrderedSet.create();
}
return this.__recordArrays;
}
get references() {
if (this._references === null) {
this._references = Object.create(null);
}
return this._references;
}
get _deferredTriggers() {
if (this.__deferredTriggers === null) {
this.__deferredTriggers = [];
}
return this.__deferredTriggers;
}
get _attributes() {
if (this.__attributes === null) {
this.__attributes = Object.create(null);
}
return this.__attributes;
}
set _attributes(v) {
this.__attributes = v;
}
get _relationships() {
if (this.__relationships === null) {
this.__relationships = new Relationships(this);
}
return this.__relationships;
}
get _inFlightAttributes() {
if (this.__inFlightAttributes === null) {
this.__inFlightAttributes = Object.create(null);
}
return this.__inFlightAttributes;
}
set _inFlightAttributes(v) {
this.__inFlightAttributes = v;
}
get _data() {
if (this.__data === null) {
this.__data = Object.create(null);
}
return this.__data;
}
set _data(v) {
this.__data = v;
}
/*
implicit relationships are relationship which have not been declared but the inverse side exists on
another record somewhere
For example if there was
```app/models/comment.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr()
})
```
but there is also
```app/models/post.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr(),
comments: DS.hasMany('comment')
})
```
would have a implicit post relationship in order to be do things like remove ourselves from the post
when we are deleted
*/
get _implicitRelationships() {
if (this.__implicitRelationships === null) {
this.__implicitRelationships = Object.create(null);
}
return this.__implicitRelationships;
}
isHiddenFromRecordArrays() {
// During dematerialization we don't want to rematerialize the record.
// recordWasDeleted can cause other records to rematerialize because it
// removes the internal model from the array and Ember arrays will always
// `objectAt(0)` and `objectAt(len -1)` to check whether `firstObject` or
// `lastObject` have changed. When this happens we don't want those
// models to rematerialize their records.
return this._isDematerializing ||
this.isDestroyed ||
this.currentState.stateName === 'root.deleted.saved' ||
this.isEmpty();
}
isEmpty() {
return this.currentState.isEmpty;
}
isLoading() {
return this.currentState.isLoading;
}
isLoaded() {
return this.currentState.isLoaded;
}
hasDirtyAttributes() {
return this.currentState.hasDirtyAttributes;
}
isSaving() {
return this.currentState.isSaving;
}
isDeleted() {
return this.currentState.isDeleted;
}
isNew() {
return this.currentState.isNew;
}
isValid() {
return this.currentState.isValid;
}
dirtyType() {
return this.currentState.dirtyType;
}
getRecord(properties) {
if (!this._record && !this._isDematerializing) {
heimdall.increment(materializeRecord);
let token = heimdall.start('InternalModel.getRecord');
// lookupFactory should really return an object that creates
// instances with the injections applied
let createOptions = {
store: this.store,
_internalModel: this,
id: this.id,
currentState: this.currentState,
isError: this.isError,
adapterError: this.error
};
if (typeof properties === 'object' && properties !== null) {
assign(createOptions, properties);
}
if (setOwner) {
// ensure that `getOwner(this)` works inside a model instance
setOwner(createOptions, getOwner(this.store));
} else {
createOptions.container = this.store.container;
}
this._record = this.store.modelFactoryFor(this.modelName).create(createOptions);
this._triggerDeferredTriggers();
heimdall.stop(token);
}
return this._record;
}
resetRecord() {
this._record = null;
this.dataHasInitialized = false;
this.isReloading = false;
this.error = null;
this.currentState = RootState.empty;
this.__attributes = null;
this.__inFlightAttributes = null;
this._data = null;
}
dematerializeRecord() {
if (this._record) {
this._isDematerializing = true;
this._record.destroy();
this.destroyRelationships();
this.updateRecordArrays();
this.resetRecord();
}
}
deleteRecord() {
this.send('deleteRecord');
}
save(options) {
let promiseLabel = "DS: Model#save " + this;
let resolver = RSVP.defer(promiseLabel);
this.store.scheduleSave(this, resolver, options);
return resolver.promise;
}
startedReloading() {
this.isReloading = true;
if (this.hasRecord) {
set(this._record, 'isReloading', true);
}
}
finishedReloading() {
this.isReloading = false;
if (this.hasRecord) {
set(this._record, 'isReloading', false);
}
}
reload() {
this.startedReloading();
let internalModel = this;
let promiseLabel = "DS: Model#reload of " + this;
return new Promise(function(resolve) {
internalModel.send('reloadRecord', resolve);
}, promiseLabel).then(function() {
internalModel.didCleanError();
return internalModel;
}, function(error) {
internalModel.didError(error);
throw error;
}, "DS: Model#reload complete, update flags").finally(function () {
internalModel.finishedReloading();
internalModel.updateRecordArrays();
});
}
/**
Computes the set of internal models reachable from `this` across exactly one
relationship.
@return {Array} An array containing the internal models that `this` belongs
to or has many.
*/
_directlyRelatedInternalModels() {
let array = [];
this.type.eachRelationship((key, relationship) => {
if (this._relationships.has(key)) {
let relationship = this._relationships.get(key);
let localRelationships = relationship.members.toArray();
let serverRelationships = relationship.canonicalMembers.toArray();
array = array.concat(localRelationships, serverRelationships);
}
});
return array;
}
/**
Computes the set of internal models reachable from this internal model.
Reachability is determined over the relationship graph (ie a graph where
nodes are internal models and edges are belongs to or has many
relationships).
@return {Array} An array including `this` and all internal models reachable
from `this`.
*/
_allRelatedInternalModels() {
let array = [];
let queue = [];
let bfsId = nextBfsId++;
queue.push(this);
this._bfsId = bfsId;
while (queue.length > 0) {
let node = queue.shift();
array.push(node);
let related = node._directlyRelatedInternalModels();
for (let i=0; i<related.length; ++i) {
let internalModel = related[i];
assert('Internal Error: seen a future bfs iteration', internalModel._bfsId <= bfsId);
if (internalModel._bfsId < bfsId) {
queue.push(internalModel);
internalModel._bfsId = bfsId;
}
}
}
return array;
}
/**
Unload the record for this internal model. This will cause the record to be
destroyed and freed up for garbage collection. It will also do a check
for cleaning up internal models.
This check is performed by first computing the set of related internal
models. If all records in this set are unloaded, then the entire set is
destroyed. Otherwise, nothing in the set is destroyed.
This means that this internal model will be freed up for garbage collection
once all models that refer to it via some relationship are also unloaded.
*/
unloadRecord() {
this.send('unloadRecord');
this.dematerializeRecord();
Ember.run.schedule('destroy', this, '_checkForOrphanedInternalModels');
}
_checkForOrphanedInternalModels() {
this._isDematerializing = false;
if (this.isDestroyed) { return; }
this._cleanupOrphanedInternalModels();
}
_cleanupOrphanedInternalModels() {
let relatedInternalModels = this._allRelatedInternalModels();
if (areAllModelsUnloaded(relatedInternalModels)) {
for (let i=0; i<relatedInternalModels.length; ++i) {
let internalModel = relatedInternalModels[i];
if (!internalModel.isDestroyed) {
internalModel.destroy();
}
}
}
}
eachRelationship(callback, binding) {
return this.modelClass.eachRelationship(callback, binding);
}
destroy() {
assert("Cannot destroy an internalModel while its record is materialized", !this._record || this._record.get('isDestroyed') || this._record.get('isDestroying'));
this.store._internalModelDestroyed(this);
this._isDestroyed = true;
}
eachAttribute(callback, binding) {
return this.modelClass.eachAttribute(callback, binding);
}
inverseFor(key) {
return this.modelClass.inverseFor(key);
}
setupData(data) {
heimdall.increment(setupData);
this.store._internalModelDidReceiveRelationshipData(this.modelName, this.id, data.relationships);
let changedKeys;
if (this.hasRecord) {
changedKeys = this._changedKeys(data.attributes);
}
assign(this._data, data.attributes);
this.pushedData();
if (this.hasRecord) {
this._record._notifyProperties(changedKeys);
}
this.didInitializeData();
}
becameReady() {
this.store.recordArrayManager.recordWasLoaded(this);
}
didInitializeData() {
if (!this.dataHasInitialized) {
this.becameReady();
this.dataHasInitialized = true;
}
}
get isDestroyed() {
return this._isDestroyed;
}
get hasRecord() {
return !!this._record;
}
/*
@method createSnapshot
@private
*/
createSnapshot(options) {
heimdall.increment(createSnapshot);
return new Snapshot(this, options);
}
/*
@method loadingData
@private
@param {Promise} promise
*/
loadingData(promise) {
this.send('loadingData', promise);
}
/*
@method loadedData
@private
*/
loadedData() {
this.send('loadedData');
this.didInitializeData();
}
/*
@method notFound
@private
*/
notFound() {
this.send('notFound');
}
/*
@method pushedData
@private
*/
pushedData() {
this.send('pushedData');
}
flushChangedAttributes() {
heimdall.increment(flushChangedAttributes);
this._inFlightAttributes = this._attributes;
this._attributes = null;
}
hasChangedAttributes() {
heimdall.increment(hasChangedAttributes);
return this.__attributes !== null && Object.keys(this.__attributes).length > 0;
}
/*
Checks if the attributes which are considered as changed are still
different to the state which is acknowledged by the server.
This method is needed when data for the internal model is pushed and the
pushed data might acknowledge dirty attributes as confirmed.
@method updateChangedAttributes
@private
*/
updateChangedAttributes() {
heimdall.increment(updateChangedAttributes);
let changedAttributes = this.changedAttributes();
let changedAttributeNames = Object.keys(changedAttributes);
let attrs = this._attributes;
for (let i = 0, length = changedAttributeNames.length; i < length; i++) {
let attribute = changedAttributeNames[i];
let data = changedAttributes[attribute];
let oldData = data[0];
let newData = data[1];
if (oldData === newData) {
delete attrs[attribute];
}
}
}
/*
Returns an object, whose keys are changed properties, and value is an
[oldProp, newProp] array.
@method changedAttributes
@private
*/
changedAttributes() {
heimdall.increment(changedAttributes);
let oldData = this._data;
let currentData = this._attributes;
let inFlightData = this._inFlightAttributes;
let newData = assign(copy(inFlightData), currentData);
let diffData = Object.create(null);
let newDataKeys = Object.keys(newData);
for (let i = 0, length = newDataKeys.length; i < length; i++) {
let key = newDataKeys[i];
diffData[key] = [oldData[key], newData[key]];
}
return diffData;
}
/*
@method adapterWillCommit
@private
*/
adapterWillCommit() {
this.send('willCommit');
}
/*
@method adapterDidDirty
@private
*/
adapterDidDirty() {
this.send('becomeDirty');
this.updateRecordArrays();
}
/*
@method send
@private
@param {String} name
@param {Object} context
*/
send(name, context) {
heimdall.increment(send);
let currentState = this.currentState;
if (!currentState[name]) {
this._unhandledEvent(currentState, name, context);
}
return currentState[name](this, context);
}
notifyHasManyAdded(key, record, idx) {
if (this.hasRecord) {
this._record.notifyHasManyAdded(key, record, idx);
}
}
notifyHasManyRemoved(key, record, idx) {
if (this.hasRecord) {
this._record.notifyHasManyRemoved(key, record, idx);
}
}
notifyBelongsToChanged(key, record) {
if (this.hasRecord) {
this._record.notifyBelongsToChanged(key, record);
}
}
notifyPropertyChange(key) {
if (this.hasRecord) {
this._record.notifyPropertyChange(key);
}
}
rollbackAttributes() {
let dirtyKeys;
if (this.hasChangedAttributes()) {
dirtyKeys = Object.keys(this._attributes);
this._attributes = null;
}
if (get(this, 'isError')) {
this._inFlightAttributes = null;
this.didCleanError();
}
//Eventually rollback will always work for relationships
//For now we support it only out of deleted state, because we
//have an explicit way of knowing when the server acked the relationship change
if (this.isDeleted()) {
//TODO: Should probably move this to the state machine somehow
this.becameReady();
}
if (this.isNew()) {
this.clearRelationships();
}
if (this.isValid()) {
this._inFlightAttributes = null;
}
this.send('rolledBack');
if (dirtyKeys && dirtyKeys.length > 0) {
this._record._notifyProperties(dirtyKeys);
}
}
/*
@method transitionTo
@private
@param {String} name
*/
transitionTo(name) {
heimdall.increment(transitionTo);
// POSSIBLE TODO: Remove this code and replace with
// always having direct reference to state objects
let pivotName = extractPivotName(name);
let state = this.currentState;
let transitionMapId = `${state.stateName}->${name}`;
do {
if (state.exit) { state.exit(this); }
state = state.parentState;
} while (!state[pivotName]);
let setups;
let enters;
let i;
let l;
let map = TransitionChainMap[transitionMapId];
if (map) {
setups = map.setups;
enters = map.enters;
state = map.state;
} else {
setups = [];
enters = [];
let path = splitOnDot(name);
for (i = 0, l = path.length; i < l; i++) {
state = state[path[i]];
if (state.enter) { enters.push(state); }
if (state.setup) { setups.push(state); }
}
TransitionChainMap[transitionMapId] = { setups, enters, state };
}
for (i = 0, l = enters.length; i < l; i++) {
enters[i].enter(this);
}
this.currentState = state;
if (this.hasRecord) {
set(this._record, 'currentState', state);
}
for (i = 0, l = setups.length; i < l; i++) {
setups[i].setup(this);
}
this.updateRecordArrays();
}
_unhandledEvent(state, name, context) {
let errorMessage = "Attempted to handle event `" + name + "` ";
errorMessage += "on " + String(this) + " while in state ";
errorMessage += state.stateName + ". ";
if (context !== undefined) {
errorMessage += "Called with " + inspect(context) + ".";
}
throw new EmberError(errorMessage);
}
triggerLater(...args) {
if (this._deferredTriggers.push(args) !== 1) {
return;
}
this.store._updateInternalModel(this);
}
_triggerDeferredTriggers() {
heimdall.increment(_triggerDeferredTriggers);
//TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record,
//but for now, we queue up all the events triggered before the record was materialized, and flush
//them once we have the record
if (!this.hasRecord) {
return;
}
let triggers = this._deferredTriggers;
let record = this._record;
let trigger = record.trigger;
for (let i = 0, l= triggers.length; i<l; i++) {
trigger.apply(record, triggers[i]);
}
triggers.length = 0;
}
/*
@method clearRelationships
@private
*/
clearRelationships() {
this.eachRelationship((name, relationship) => {
if (this._relationships.has(name)) {
let rel = this._relationships.get(name);
rel.clear();
rel.removeInverseRelationships();
}
});
Object.keys(this._implicitRelationships).forEach((key) => {
this._implicitRelationships[key].clear();
this._implicitRelationships[key].removeInverseRelationships();
});
}
destroyRelationships() {
this.eachRelationship((name, relationship) => {
if (this._relationships.has(name)) {
let rel = this._relationships.get(name);
rel.removeInverseRelationships();
}
});
Object.keys(this._implicitRelationships).forEach((key) => {
this._implicitRelationships[key].removeInverseRelationships();
});
}
/*
When a find request is triggered on the store, the user can optionally pass in
attributes and relationships to be preloaded. These are meant to behave as if they
came back from the server, except the user obtained them out of band and is informing
the store of their existence. The most common use case is for supporting client side
nested URLs, such as `/posts/1/comments/2` so the user can do
`store.findRecord('comment', 2, { preload: { post: 1 } })` without having to fetch the post.
Preloaded data can be attributes and relationships passed in either as IDs or as actual
models.
@method preloadData
@private
@param {Object} preload
*/
preloadData(preload) {
//TODO(Igor) consider the polymorphic case
Object.keys(preload).forEach((key) => {
let preloadValue = get(preload, key);
let relationshipMeta = this.modelClass.metaForProperty(key);
if (relationshipMeta.isRelationship) {
this._preloadRelationship(key, preloadValue);
} else {
this._data[key] = preloadValue;
}
});
}
_preloadRelationship(key, preloadValue) {
let relationshipMeta = this.modelClass.metaForProperty(key);
let modelClass = relationshipMeta.type;
if (relationshipMeta.kind === 'hasMany') {
this._preloadHasMany(key, preloadValue, modelClass);
} else {
this._preloadBelongsTo(key, preloadValue, modelClass);
}
}
_preloadHasMany(key, preloadValue, modelClass) {
assert("You need to pass in an array to set a hasMany property on a record", Array.isArray(preloadValue));
let recordsToSet = new Array(preloadValue.length);
for (let i = 0; i < preloadValue.length; i++) {
let recordToPush = preloadValue[i];
recordsToSet[i] = this._convertStringOrNumberIntoInternalModel(recordToPush, modelClass);
}
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).updateInternalModelsFromAdapter(recordsToSet);
}
_preloadBelongsTo(key, preloadValue, modelClass) {
let internalModelToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, modelClass);
//We use the pathway of setting the hasMany as if it came from the adapter
//because the user told us that they know this relationships exists already
this._relationships.get(key).setInternalModel(internalModelToSet);
}
_convertStringOrNumberIntoInternalModel(value, modelClass) {
if (typeof value === 'string' || typeof value === 'number') {
return this.store._internalModelForId(modelClass, value);
}
if (value._internalModel) {
return value._internalModel;
}
return value;
}
/*
@method updateRecordArrays
@private
*/
updateRecordArrays() {
this.store.recordArrayManager.recordDidChange(this);
}
setId(id) {
assert('A record\'s id cannot be changed once it is in the loaded state', this.id === null || this.id === id || this.isNew());
this.id = id;
if (this._record.get('id') !== id) {
this._record.set('id', id);
}
}
didError(error) {
this.error = error;
this.isError = true;
if (this.hasRecord) {
this._record.setProperties({
isError: true,
adapterError: error
});
}
}
didCleanError() {
this.error = null;