-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
internal-model.ts
1679 lines (1444 loc) · 49 KB
/
internal-model.ts
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 { set, get } from '@ember/object';
import EmberError from '@ember/error';
import { default as EmberArray, A } from '@ember/array';
import { setOwner, getOwner } from '@ember/application';
import { assign } from '@ember/polyfills';
import { run } from '@ember/runloop';
import RSVP, { Promise, resolve } from 'rsvp';
import Ember from 'ember';
import { DEBUG } from '@glimmer/env';
import { assert, inspect } from '@ember/debug';
import { deprecate } from '@ember/application/deprecations';
import Model from './model';
import RootState from './states';
import Snapshot from '../snapshot';
import OrderedSet from '../ordered-set';
import ManyArray from '../many-array';
import { PromiseBelongsTo, PromiseManyArray } from '../promise-proxies';
import Store from '../ds-model-store';
import { errorsHashToArray, errorsArrayToHash } from '../errors-utils';
import { RecordReference, BelongsToReference, HasManyReference } from '../references';
import { default as recordDataFor, relationshipStateFor } from '../record-data-for';
import RecordData from '../../ts-interfaces/record-data';
import { JsonApiResource, JsonApiValidationError } from '../../ts-interfaces/record-data-json-api';
import { Record } from '../../ts-interfaces/record';
import { Dict } from '../../ts-interfaces/utils';
import {
IDENTIFIERS,
RECORD_DATA_ERRORS,
RECORD_DATA_STATE,
REQUEST_SERVICE,
CUSTOM_MODEL_CLASS,
} from '@ember-data/canary-features';
import { identifierCacheFor } from '../../identifiers/cache';
import { StableRecordIdentifier } from '../../ts-interfaces/identifier';
import { internalModelFactoryFor, setRecordIdentifier } from '../store/internal-model-factory';
import CoreStore from '../core-store';
import coerceId from '../coerce-id';
/**
@module @ember-data/store
*/
// move to TS hacks module that we can delete when this is no longer a necessary recast
type ManyArray = InstanceType<typeof ManyArray>;
type PromiseBelongsTo = InstanceType<typeof PromiseBelongsTo>;
type PromiseManyArray = InstanceType<typeof PromiseManyArray>;
// TODO this should be integrated with the code removal so we can use it together with the if condition
// and not alongside it
function isNotCustomModelClass(store: CoreStore | Store): store is Store {
return !CUSTOM_MODEL_CLASS;
}
interface BelongsToMetaWrapper {
key: string;
store: CoreStore;
originatingInternalModel: InternalModel;
modelName: string;
}
let INSTANCE_DEPRECATIONS;
let lookupDeprecations;
if (DEBUG) {
INSTANCE_DEPRECATIONS = new WeakMap();
lookupDeprecations = function lookupInstanceDrecations(instance) {
let deprecations = INSTANCE_DEPRECATIONS.get(instance);
if (!deprecations) {
deprecations = {};
INSTANCE_DEPRECATIONS.set(instance, deprecations);
}
return deprecations;
};
}
/*
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]);
}
/*
`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 `Model` to application code, by materializing a `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 {
_id: string | null;
modelName: string;
clientId: string;
__recordData: RecordData | null;
_isDestroyed: boolean;
isError: boolean;
_pendingRecordArrayManagerFlush: boolean;
_isDematerializing: boolean;
isReloading: boolean;
_doNotDestroy: boolean;
isDestroying: boolean;
// Not typed yet
_promiseProxy: any;
_record: any;
_scheduledDestroy: any;
_modelClass: any;
__deferredTriggers: any;
__recordArrays: any;
_references: any;
_recordReference: any;
_manyArrayCache: Dict<string, ManyArray> = Object.create(null);
// The previous ManyArrays for this relationship which will be destroyed when
// we create a new ManyArray, but in the interim the retained version will be
// updated if inverse internal models are unloaded.
_retainedManyArrayCache: Dict<string, ManyArray> = Object.create(null);
_relationshipPromisesCache: Dict<string, RSVP.Promise<any>> = Object.create(null);
_relationshipProxyCache: Dict<string, PromiseManyArray | PromiseBelongsTo> = Object.create(null);
currentState: any;
error: any;
constructor(public store: CoreStore | Store, public identifier: StableRecordIdentifier) {
this._id = identifier.id;
this.modelName = identifier.type;
this.clientId = identifier.lid;
this.__recordData = null;
// this ensure ordered set can quickly identify this as unique
this[Ember.GUID_KEY] = identifier.lid;
this._promiseProxy = null;
this._record = null;
this._isDestroyed = false;
this.isError = false;
this._pendingRecordArrayManagerFlush = 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._scheduledDestroy = null;
this.resetRecord();
// caches for lazy getters
this._modelClass = null;
this.__deferredTriggers = null;
this.__recordArrays = null;
this._references = null;
this._recordReference = null;
}
get id(): string | null {
if (IDENTIFIERS) {
return this.identifier.id; // || this._id;
}
return this._id;
}
set id(value: string | null) {
if (IDENTIFIERS) {
if (value !== this._id) {
let newIdentifier = { type: this.identifier.type, lid: this.identifier.lid, id: value };
identifierCacheFor(this.store).updateRecordIdentifier(this.identifier, newIdentifier);
// TODO Show deprecation for private api
}
} else if (!IDENTIFIERS) {
this._id = value;
}
}
get modelClass() {
if (this.store.modelFor) {
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 _recordData(): RecordData {
if (this.__recordData === null) {
let recordData = this.store._createRecordData(this.identifier);
this._recordData = recordData;
return recordData;
}
return this.__recordData;
}
set _recordData(newValue) {
this.__recordData = newValue;
}
get _recordArrays() {
if (this.__recordArrays === null) {
this.__recordArrays = new OrderedSet();
}
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;
}
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.
// eager checks to avoid instantiating record data if we are empty or loading
if (this.isEmpty()) {
return true;
}
if (RECORD_DATA_STATE) {
if (this.isLoading()) {
return false;
}
}
let isRecordFullyDeleted;
if (RECORD_DATA_STATE) {
isRecordFullyDeleted = this._isRecordFullyDeleted();
} else {
isRecordFullyDeleted = this.currentState.stateName === 'root.deleted.saved';
}
return this._isDematerializing || this.hasScheduledDestroy() || this.isDestroyed || isRecordFullyDeleted;
}
_isRecordFullyDeleted(): boolean {
if (RECORD_DATA_STATE) {
if (this._recordData.isDeletionCommitted && this._recordData.isDeletionCommitted()) {
return true;
} else if (
this._recordData.isNew &&
this._recordData.isDeleted &&
this._recordData.isNew() &&
this._recordData.isDeleted()
) {
return true;
} else {
return this.currentState.stateName === 'root.deleted.saved';
}
} else {
// assert here
return false;
}
}
isRecordInUse() {
let record = this._record;
return record && !(record.get('isDestroyed') || record.get('isDestroying'));
}
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() {
if (RECORD_DATA_STATE) {
if (this._recordData.isDeleted) {
return this._recordData.isDeleted();
} else {
return this.currentState.isDeleted;
}
} else {
return this.currentState.isDeleted;
}
}
isNew() {
if (RECORD_DATA_STATE) {
if (this._recordData.isNew) {
return this._recordData.isNew();
} else {
return this.currentState.isNew;
}
} else {
return this.currentState.isNew;
}
}
isValid() {
if (RECORD_DATA_ERRORS) {
} else {
return this.currentState.isValid;
}
}
dirtyType() {
return this.currentState.dirtyType;
}
getRecord(properties?) {
if (!this._record && !this._isDematerializing) {
let { store } = this;
if (CUSTOM_MODEL_CLASS) {
this._record = store._instantiateRecord(this, this.modelName, this._recordData, this.identifier, properties);
} else {
if (isNotCustomModelClass(store)) {
// lookupFactory should really return an object that creates
// instances with the injections applied
let createOptions: any = {
store,
_internalModel: this,
currentState: this.currentState,
};
if (!REQUEST_SERVICE) {
createOptions.isError = this.isError;
createOptions.adapterError = this.error;
}
if (properties !== undefined) {
assert(
`You passed '${properties}' as properties for record creation instead of an object.`,
typeof properties === 'object' && properties !== null
);
if ('id' in properties) {
const id = coerceId(properties.id);
if (id !== null) {
this.setId(id);
}
}
// convert relationship Records to RecordDatas before passing to RecordData
let defs = store._relationshipsDefinitionFor(this.modelName);
if (defs !== null) {
let keys = Object.keys(properties);
let relationshipValue;
for (let i = 0; i < keys.length; i++) {
let prop = keys[i];
let def = defs[prop];
if (def !== undefined) {
if (def.kind === 'hasMany') {
if (DEBUG) {
assertRecordsPassedToHasMany(properties[prop]);
}
relationshipValue = extractRecordDatasFromRecords(properties[prop]);
} else {
relationshipValue = extractRecordDataFromRecord(properties[prop]);
}
properties[prop] = relationshipValue;
}
}
}
}
let additionalCreateOptions = this._recordData._initRecordCreateOptions(properties);
assign(createOptions, additionalCreateOptions);
// ensure that `getOwner(this)` works inside a model instance
setOwner(createOptions, getOwner(store));
this._record = store._modelFactoryFor(this.modelName).create(createOptions);
setRecordIdentifier(this._record, this.identifier);
if (DEBUG) {
let klass = this._record.constructor;
let deprecations = lookupDeprecations(klass);
[
'becameError',
'becameInvalid',
'didCreate',
'didDelete',
'didLoad',
'didUpdate',
'ready',
'rolledBack',
].forEach(methodName => {
if (this instanceof Model && typeof this._record[methodName] === 'function') {
deprecate(
`Attempted to define ${methodName} on ${this._record.modelName}#${this._record.id}`,
deprecations[methodName],
{
id: 'ember-data:record-lifecycle-event-methods',
until: '4.0',
}
);
}
});
}
}
}
this._triggerDeferredTriggers();
}
return this._record;
}
resetRecord() {
this._record = null;
this.isReloading = false;
this.error = null;
this.currentState = RootState.empty;
}
dematerializeRecord() {
this._isDematerializing = true;
// TODO IGOR add a test that fails when this is missing, something that involves canceliing a destroy
// and the destroy not happening, and then later on trying to destroy
this._doNotDestroy = false;
if (this._record) {
if (CUSTOM_MODEL_CLASS) {
this.store.teardownRecord(this._record);
} else {
this._record.destroy();
}
Object.keys(this._relationshipProxyCache).forEach(key => {
if (this._relationshipProxyCache[key].destroy) {
this._relationshipProxyCache[key].destroy();
}
delete this._relationshipProxyCache[key];
});
Object.keys(this._manyArrayCache).forEach(key => {
let manyArray = (this._retainedManyArrayCache[key] = this._manyArrayCache[key]);
delete this._manyArrayCache[key];
if (manyArray && !manyArray._inverseIsAsync) {
/*
If the manyArray is for a sync relationship, we should clear it
to preserve the semantics of client-side delete.
It is likely in this case instead of retaining we should destroy
- @runspired
*/
manyArray.clear();
}
});
}
// move to an empty never-loaded state
this._recordData.unloadRecord();
this.resetRecord();
this.updateRecordArrays();
}
deleteRecord() {
if (RECORD_DATA_STATE) {
if (this._recordData.setIsDeleted) {
this._recordData.setIsDeleted(true);
}
}
this.send('deleteRecord');
}
save(options) {
let promiseLabel = 'DS: Model#save ' + this;
let resolver = RSVP.defer<InternalModel>(promiseLabel);
if (REQUEST_SERVICE) {
// Casting to narrow due to the feature flag paths inside scheduleSave
return this.store.scheduleSave(this, resolver, options) as RSVP.Promise<void>;
} else {
this.store.scheduleSave(this, resolver, options);
return resolver.promise;
}
}
startedReloading() {
this.isReloading = true;
if (this.hasRecord) {
set(this._record, 'isReloading', true);
}
}
linkWasLoadedForRelationship(key, data) {
let relationships = {};
relationships[key] = data;
this._recordData.pushData({
id: this.id,
type: this.modelName,
relationships,
});
}
finishedReloading() {
this.isReloading = false;
if (this.hasRecord) {
set(this._record, 'isReloading', false);
}
}
reload(options) {
if (REQUEST_SERVICE) {
if (!options) {
options = {};
}
this.startedReloading();
let internalModel = this;
let promiseLabel = 'DS: Model#reload of ' + this;
return internalModel.store
._reloadRecord(internalModel, options)
.then(
function() {
//TODO NOW seems like we shouldn't need to do this
return internalModel;
},
function(error) {
throw error;
},
'DS: Model#reload complete, update flags'
)
.finally(function() {
internalModel.finishedReloading();
internalModel.updateRecordArrays();
});
} else {
this.startedReloading();
let internalModel = this;
let promiseLabel = 'DS: Model#reload of ' + this;
return new Promise(function(resolve) {
internalModel.send('reloadRecord', { resolve, options });
}, 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();
});
}
}
/*
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() {
if (this.isDestroyed) {
return;
}
this.send('unloadRecord');
this.dematerializeRecord();
if (this._scheduledDestroy === null) {
this._scheduledDestroy = run.backburner.schedule('destroy', this, '_checkForOrphanedInternalModels');
}
}
hasScheduledDestroy() {
return !!this._scheduledDestroy;
}
cancelDestroy() {
assert(
`You cannot cancel the destruction of an InternalModel once it has already been destroyed`,
!this.isDestroyed
);
this._doNotDestroy = true;
this._isDematerializing = false;
run.cancel(this._scheduledDestroy);
this._scheduledDestroy = null;
}
// typically, we prefer to async destroy this lets us batch cleanup work.
// Unfortunately, some scenarios where that is not possible. Such as:
//
// ```js
// const record = store.find(‘record’, 1);
// record.unloadRecord();
// store.createRecord(‘record’, 1);
// ```
//
// In those scenarios, we make that model's cleanup work, sync.
//
destroySync() {
if (this._isDematerializing) {
this.cancelDestroy();
}
this._checkForOrphanedInternalModels();
if (this.isDestroyed || this.isDestroying) {
return;
}
// just in-case we are not one of the orphaned, we should still
// still destroy ourselves
this.destroy();
}
_checkForOrphanedInternalModels() {
this._isDematerializing = false;
this._scheduledDestroy = null;
if (this.isDestroyed) {
return;
}
}
eachRelationship(callback, binding) {
return this.modelClass.eachRelationship(callback, binding);
}
_findBelongsTo(key, resource, relationshipMeta, options) {
// TODO @runspired follow up if parent isNew then we should not be attempting load here
return this.store
._findBelongsToByJsonApiResource(resource, this, relationshipMeta, options)
.then(
internalModel => handleCompletedRelationshipRequest(this, key, resource._relationship, internalModel, null),
e => handleCompletedRelationshipRequest(this, key, resource._relationship, null, e)
);
}
getBelongsTo(key, options) {
let resource = this._recordData.getBelongsTo(key);
let identifier =
resource && resource.data ? identifierCacheFor(this.store).getOrCreateRecordIdentifier(resource.data) : null;
let relationshipMeta = this.store._relationshipMetaFor(this.modelName, null, key);
let store = this.store;
let parentInternalModel = this;
let async = relationshipMeta.options.async;
let isAsync = typeof async === 'undefined' ? true : async;
let _belongsToState: BelongsToMetaWrapper = {
key,
store,
originatingInternalModel: this,
modelName: relationshipMeta.type,
};
if (isAsync) {
let internalModel = identifier !== null ? store._internalModelForResource(identifier) : null;
if (resource!._relationship!.hasFailedLoadAttempt) {
return this._relationshipProxyCache[key];
}
let promise = this._findBelongsTo(key, resource, relationshipMeta, options);
return this._updatePromiseProxyFor('belongsTo', key, {
promise,
content: internalModel ? internalModel.getRecord() : null,
_belongsToState,
});
} else {
if (identifier === null) {
return null;
} else {
let internalModel = store._internalModelForResource(identifier);
let toReturn = internalModel.getRecord();
assert(
"You looked up the '" +
key +
"' relationship on a '" +
parentInternalModel.modelName +
"' with id " +
parentInternalModel.id +
' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)',
toReturn === null || !toReturn.get('isEmpty')
);
return toReturn;
}
}
}
// TODO Igor consider getting rid of initial state
getManyArray(key, isAsync = false) {
let relationshipMeta = this.store._relationshipMetaFor(this.modelName, null, key);
let jsonApi = this._recordData.getHasMany(key);
let manyArray = this._manyArrayCache[key];
assert(
`Error: relationship ${this.modelName}:${key} has both many array and retained many array`,
!manyArray || !this._retainedManyArrayCache[key]
);
if (!manyArray) {
let initialState = this.store._getHasManyByJsonApiResource(jsonApi);
// TODO move this to a public api
let inverseIsAsync = jsonApi._relationship ? jsonApi._relationship._inverseIsAsync() : false;
manyArray = ManyArray.create({
store: this.store,
type: this.store.modelFor(relationshipMeta.type),
recordData: this._recordData,
meta: jsonApi.meta,
key,
isPolymorphic: relationshipMeta.options.polymorphic,
initialState: initialState.slice(),
_inverseIsAsync: inverseIsAsync,
internalModel: this,
isLoaded: !isAsync,
});
this._manyArrayCache[key] = manyArray;
}
if (this._retainedManyArrayCache[key]) {
this._retainedManyArrayCache[key].destroy();
delete this._retainedManyArrayCache[key];
}
return manyArray;
}
fetchAsyncHasMany(key, relationshipMeta, jsonApi, manyArray, options): RSVP.Promise<unknown> {
// TODO @runspired follow up if parent isNew then we should not be attempting load here
let loadingPromise = this._relationshipPromisesCache[key];
if (loadingPromise) {
return loadingPromise;
}
loadingPromise = this.store
._findHasManyByJsonApiResource(jsonApi, this, relationshipMeta, options)
.then(initialState => {
// TODO why don't we do this in the store method
manyArray.retrieveLatest();
manyArray.set('isLoaded', true);
return manyArray;
})
.then(
manyArray => handleCompletedRelationshipRequest(this, key, jsonApi._relationship, manyArray, null),
e => handleCompletedRelationshipRequest(this, key, jsonApi._relationship, null, e)
);
this._relationshipPromisesCache[key] = loadingPromise;
return loadingPromise;
}
getHasMany(key, options) {
let jsonApi = this._recordData.getHasMany(key);
let relationshipMeta = this.store._relationshipMetaFor(this.modelName, null, key);
let async = relationshipMeta.options.async;
let isAsync = typeof async === 'undefined' ? true : async;
let manyArray = this.getManyArray(key, isAsync);
if (isAsync) {
if (jsonApi!._relationship!.hasFailedLoadAttempt) {
return this._relationshipProxyCache[key];
}
let promise = this.fetchAsyncHasMany(key, relationshipMeta, jsonApi, manyArray, options);
return this._updatePromiseProxyFor('hasMany', key, { promise, content: manyArray });
} else {
assert(
`You looked up the '${key}' relationship on a '${this.type.modelName}' with id ${this.id} but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async ('DS.hasMany({ async: true })')`,
!manyArray.anyUnloaded()
);
return manyArray;
}
}
_updatePromiseProxyFor(
kind: 'hasMany' | 'belongsTo',
key: string,
args: {
promise: RSVP.Promise<any>;
content?: Record | ManyArray | null;
_belongsToState?: BelongsToMetaWrapper;
}
) {
let promiseProxy = this._relationshipProxyCache[key];
if (promiseProxy) {
if (args.content !== undefined) {
// this usage of `any` can be removed when `@types/ember_object` proxy allows `null` for content
promiseProxy.set('content', args.content as any);
}
promiseProxy.set('promise', args.promise);
} else {
const klass = kind === 'hasMany' ? PromiseManyArray : PromiseBelongsTo;
// this usage of `any` can be removed when `@types/ember_object` proxy allows `null` for content
this._relationshipProxyCache[key] = klass.create(args as any);
}
return this._relationshipProxyCache[key];
}
reloadHasMany(key, options) {
let loadingPromise = this._relationshipPromisesCache[key];
if (loadingPromise) {
return loadingPromise;
}
let jsonApi = this._recordData.getHasMany(key);
// TODO move this to a public api
if (jsonApi._relationship) {
jsonApi._relationship.setHasFailedLoadAttempt(false);
jsonApi._relationship.setShouldForceReload(true);
}
let relationshipMeta = this.store._relationshipMetaFor(this.modelName, null, key);
let manyArray = this.getManyArray(key);
let promise = this.fetchAsyncHasMany(key, relationshipMeta, jsonApi, manyArray, options);
if (this._relationshipProxyCache[key]) {
return this._updatePromiseProxyFor('hasMany', key, { promise });
}
return promise;
}
reloadBelongsTo(key, options) {
let loadingPromise = this._relationshipPromisesCache[key];
if (loadingPromise) {
return loadingPromise;
}
let resource = this._recordData.getBelongsTo(key);
// TODO move this to a public api
if (resource._relationship) {
resource._relationship.setHasFailedLoadAttempt(false);
resource._relationship.setShouldForceReload(true);
}
let relationshipMeta = this.store._relationshipMetaFor(this.modelName, null, key);
let promise = this._findBelongsTo(key, resource, relationshipMeta, options);
if (this._relationshipProxyCache[key]) {
return this._updatePromiseProxyFor('belongsTo', key, { promise });
}
return promise;
}
destroyFromRecordData() {
if (this._doNotDestroy) {
this._doNotDestroy = false;
return;
}
this.destroy();
}
destroy() {
assert(
'Cannot destroy an internalModel while its record is materialized',
!this._record || this._record.get('isDestroyed') || this._record.get('isDestroying')
);
this.isDestroying = true;
Object.keys(this._retainedManyArrayCache).forEach(key => {
this._retainedManyArrayCache[key].destroy();
delete this._retainedManyArrayCache[key];
});
internalModelFactoryFor(this.store).remove(this);
this._isDestroyed = true;
}
eachAttribute(callback, binding) {
return this.modelClass.eachAttribute(callback, binding);
}
inverseFor(key) {
return this.modelClass.inverseFor(key);
}
setupData(data) {
let changedKeys = this._recordData.pushData(data, this.hasRecord);
if (this.hasRecord) {
this._record._notifyProperties(changedKeys);
}
this.pushedData();
}
getAttributeValue(key) {
return this._recordData.getAttr(key);
}
setDirtyHasMany(key, records) {
assertRecordsPassedToHasMany(records);
return this._recordData.setDirtyHasMany(key, extractRecordDatasFromRecords(records));
}
setDirtyBelongsTo(key, value) {
return this._recordData.setDirtyBelongsTo(key, extractRecordDataFromRecord(value));
}
setDirtyAttribute(key, value) {
if (this.isDeleted()) {
throw new EmberError(`Attempted to set '${key}' to '${value}' on the deleted record ${this}`);
}
let currentValue = this.getAttributeValue(key);
if (currentValue !== value) {
this._recordData.setDirtyAttribute(key, value);
let isDirty = this._recordData.isAttrDirty(key);
this.send('didSetProperty', {
name: key,
isDirty: isDirty,
});
}
return value;
}
get isDestroyed() {
return this._isDestroyed;
}
get hasRecord() {
return !!this._record;
}
/*
@method createSnapshot
@private
*/
createSnapshot(options) {
return new Snapshot(options || {}, this.identifier, this.store);
}
/*
@method loadingData
@private
@param {Promise} promise
*/
loadingData(promise?) {
if (REQUEST_SERVICE) {
this.send('loadingData');
} else {
this.send('loadingData', promise);