forked from emberjs/data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.ts
1734 lines (1567 loc) · 55.3 KB
/
cache.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
/**
* @module @ember-data/json-api
*/
import { assert } from '@ember/debug';
import { LOG_MUTATIONS, LOG_OPERATIONS, LOG_REQUESTS } from '@ember-data/debugging';
import { DEPRECATE_RELATIONSHIP_REMOTE_UPDATE_CLEARING_LOCAL_STATE } from '@ember-data/deprecations';
import { DEBUG } from '@ember-data/env';
import { graphFor, peekGraph } from '@ember-data/graph/-private';
import type { LocalRelationshipOperation } from '@ember-data/graph/-private/-operations';
import type { CollectionEdge } from '@ember-data/graph/-private/edges/collection';
import type { ImplicitEdge } from '@ember-data/graph/-private/edges/implicit';
import type { ResourceEdge } from '@ember-data/graph/-private/edges/resource';
import type { Graph, GraphEdge } from '@ember-data/graph/-private/graph';
import { StructuredErrorDocument } from '@ember-data/request/-private/types';
import { StoreRequestInfo } from '@ember-data/store/-private/cache-handler';
import type { IdentifierCache } from '@ember-data/store/-private/caches/identifier-cache';
import type { ResourceBlob } from '@ember-data/types/cache/aliases';
import type { RelationshipDiff } from '@ember-data/types/cache/cache';
import type { Change } from '@ember-data/types/cache/change';
import type {
CollectionResourceDataDocument,
ResourceDocument,
ResourceErrorDocument,
ResourceMetaDocument,
SingleResourceDataDocument,
StructuredDataDocument,
StructuredDocument,
} from '@ember-data/types/cache/document';
import type { StableDocumentIdentifier } from '@ember-data/types/cache/identifier';
import type { Cache, ChangedAttributesHash, MergeOperation } from '@ember-data/types/q/cache';
import type { CacheCapabilitiesManager } from '@ember-data/types/q/cache-store-wrapper';
import type {
CollectionResourceDocument,
CollectionResourceRelationship,
ExistingResourceObject,
SingleResourceDocument,
SingleResourceRelationship,
} from '@ember-data/types/q/ember-data-json-api';
import type { StableExistingRecordIdentifier, StableRecordIdentifier } from '@ember-data/types/q/identifier';
import type { AttributesHash, JsonApiError, JsonApiResource } from '@ember-data/types/q/record-data-json-api';
import type { AttributeSchema, RelationshipSchema } from '@ember-data/types/q/record-data-schemas';
function isImplicit(relationship: GraphEdge): relationship is ImplicitEdge {
return relationship.definition.isImplicit;
}
const EMPTY_ITERATOR = {
iterator() {
return {
next() {
return { done: true, value: undefined };
},
};
},
};
interface CachedResource {
id: string | null;
remoteAttrs: Record<string, unknown> | null;
localAttrs: Record<string, unknown> | null;
inflightAttrs: Record<string, unknown> | null;
changes: Record<string, unknown[]> | null;
errors: JsonApiError[] | null;
isNew: boolean;
isDeleted: boolean;
isDeletionCommitted: boolean;
}
function makeCache(): CachedResource {
return {
id: null,
remoteAttrs: null,
localAttrs: null,
inflightAttrs: null,
changes: null,
errors: null,
isNew: false,
isDeleted: false,
isDeletionCommitted: false,
};
}
/**
A JSON:API Cache implementation.
What cache the store uses is configurable. Using a different
implementation can be achieved by implementing the store's
createCache hook.
This is the cache implementation used by `ember-data`.
```js
import Cache from '@ember-data/json-api';
import Store from '@ember-data/store';
export default class extends Store {
createCache(wrapper) {
return new Cache(wrapper);
}
}
```
@class Cache
@public
*/
export default class JSONAPICache implements Cache {
/**
* The Cache Version that this implementation implements.
*
* @type {'2'}
* @public
* @property version
*/
declare version: '2';
declare __storeWrapper: CacheCapabilitiesManager;
declare __cache: Map<StableRecordIdentifier, CachedResource>;
declare __destroyedCache: Map<StableRecordIdentifier, CachedResource>;
declare __documents: Map<string, StructuredDocument<ResourceDocument>>;
declare __graph: Graph;
constructor(storeWrapper: CacheCapabilitiesManager) {
this.version = '2';
this.__storeWrapper = storeWrapper;
this.__cache = new Map();
this.__graph = graphFor(storeWrapper);
this.__destroyedCache = new Map();
this.__documents = new Map();
}
// Cache Management
// ================
/**
* Cache the response to a request
*
* Implements `Cache.put`.
*
* Expects a StructuredDocument whose `content` member is a JsonApiDocument.
*
* ```js
* cache.put({
* request: { url: 'https://api.example.com/v1/user/1' },
* content: {
* data: {
* type: 'user',
* id: '1',
* attributes: {
* name: 'Chris'
* }
* }
* }
* })
* ```
*
* > **Note:** The nested `content` and `data` members are not a mistake. This is because
* > there are two separate concepts involved here, the `StructuredDocument` which contains
* > the context of a given Request that has been issued with the returned contents as its
* > `content` property, and a `JSON:API Document` which is the json contents returned by
* > this endpoint and which uses its `data` property to signify which resources are the
* > primary resources associated with the request.
*
* StructuredDocument's with urls will be cached as full documents with
* associated resource membership order and contents preserved but linked
* into the cache.
*
* @method put
* @param {StructuredDocument} doc
* @returns {ResourceDocument}
* @public
*/
put<T extends SingleResourceDocument>(doc: StructuredDocument<T>): SingleResourceDataDocument;
put<T extends CollectionResourceDocument>(doc: StructuredDocument<T>): CollectionResourceDataDocument;
put<T extends ResourceErrorDocument>(doc: StructuredErrorDocument<T>): ResourceErrorDocument;
put<T extends ResourceMetaDocument>(doc: StructuredDataDocument<T>): ResourceMetaDocument;
put(doc: StructuredDocument<ResourceDocument>): ResourceDocument {
assert(
`Expected a JSON:API Document as the content provided to the cache, received ${doc.content}`,
doc instanceof Error || (typeof doc.content === 'object' && doc.content !== null)
);
if (isErrorDocument(doc)) {
return this._putDocument(doc as StructuredErrorDocument<ResourceErrorDocument>, undefined, undefined);
} else if (isMetaDocument(doc)) {
return this._putDocument(doc, undefined, undefined);
}
const jsonApiDoc = doc.content as SingleResourceDocument | CollectionResourceDocument;
let included = jsonApiDoc.included;
let i: number, length: number;
const { identifierCache } = this.__storeWrapper;
if (LOG_REQUESTS) {
const Counts = new Map();
if (included) {
for (i = 0, length = included.length; i < length; i++) {
const type = included[i].type;
Counts.set(type, (Counts.get(type) || 0) + 1);
}
}
if (Array.isArray(jsonApiDoc.data)) {
for (i = 0, length = jsonApiDoc.data.length; i < length; i++) {
const type = jsonApiDoc.data[i].type;
Counts.set(type, (Counts.get(type) || 0) + 1);
}
} else if (jsonApiDoc.data) {
const type = jsonApiDoc.data.type;
Counts.set(type, (Counts.get(type) || 0) + 1);
}
let str = `JSON:API Cache - put (${doc.content?.lid || doc.request?.url || 'unknown-request'})\n\tContents:`;
Counts.forEach((count, type) => {
str += `\n\t\t${type}: ${count}`;
});
if (Counts.size === 0) {
str += `\t(empty)`;
}
// eslint-disable-next-line no-console
console.log(str);
}
if (included) {
for (i = 0, length = included.length; i < length; i++) {
included[i] = putOne(this, identifierCache, included[i]);
}
}
if (Array.isArray(jsonApiDoc.data)) {
length = jsonApiDoc.data.length;
let identifiers: StableExistingRecordIdentifier[] = [];
for (i = 0; i < length; i++) {
identifiers.push(putOne(this, identifierCache, jsonApiDoc.data[i]));
}
return this._putDocument(
doc as StructuredDataDocument<CollectionResourceDocument>,
identifiers,
included as StableExistingRecordIdentifier[]
);
}
if (jsonApiDoc.data === null) {
return this._putDocument(
doc as StructuredDataDocument<SingleResourceDocument>,
null,
included as StableExistingRecordIdentifier[]
);
}
assert(
`Expected a resource object in the 'data' property in the document provided to the cache, but was ${typeof jsonApiDoc.data}`,
typeof jsonApiDoc.data === 'object'
);
let identifier = putOne(this, identifierCache, jsonApiDoc.data);
return this._putDocument(
doc as StructuredDataDocument<SingleResourceDocument>,
identifier,
included as StableExistingRecordIdentifier[]
);
}
_putDocument<T extends ResourceErrorDocument>(
doc: StructuredErrorDocument<T>,
data: undefined,
included: undefined
): ResourceErrorDocument;
_putDocument<T extends ResourceMetaDocument>(
doc: StructuredDataDocument<T>,
data: undefined,
included: undefined
): ResourceMetaDocument;
_putDocument<T extends SingleResourceDocument>(
doc: StructuredDataDocument<T>,
data: StableExistingRecordIdentifier | null,
included: StableExistingRecordIdentifier[] | undefined
): SingleResourceDataDocument;
_putDocument<T extends CollectionResourceDocument>(
doc: StructuredDataDocument<T>,
data: StableExistingRecordIdentifier[],
included: StableExistingRecordIdentifier[] | undefined
): CollectionResourceDataDocument;
_putDocument<T extends ResourceDocument>(
doc: StructuredDocument<T>,
data: StableExistingRecordIdentifier[] | StableExistingRecordIdentifier | null | undefined,
included: StableExistingRecordIdentifier[] | undefined
): SingleResourceDataDocument | CollectionResourceDataDocument | ResourceErrorDocument | ResourceMetaDocument {
// @ts-expect-error narrowing within is just horrible in TS :/
const resourceDocument: SingleResourceDataDocument | CollectionResourceDataDocument | ResourceErrorDocument =
isErrorDocument(doc) ? fromStructuredError(doc) : fromBaseDocument(doc);
if (data !== undefined) {
(resourceDocument as SingleResourceDataDocument | CollectionResourceDataDocument).data = data;
}
if (included !== undefined) {
assert(`There should not be included data on an Error document`, !isErrorDocument(doc));
assert(`There should not be included data on a Meta document`, !isMetaDocument(doc));
(resourceDocument as SingleResourceDataDocument | CollectionResourceDataDocument).included = included;
}
const request = doc.request as StoreRequestInfo | undefined;
const identifier = request ? this.__storeWrapper.identifierCache.getOrCreateDocumentIdentifier(request) : null;
if (identifier) {
resourceDocument.lid = identifier.lid;
// @ts-expect-error
doc.content = resourceDocument;
const hasExisting = this.__documents.has(identifier.lid);
this.__documents.set(identifier.lid, doc as StructuredDocument<ResourceDocument>);
this.__storeWrapper.notifyChange(identifier, hasExisting ? 'updated' : 'added');
}
return resourceDocument;
}
/**
* Update the "remote" or "canonical" (persisted) state of the Cache
* by merging new information into the existing state.
*
* Note: currently the only valid resource operation is a MergeOperation
* which occurs when a collision of identifiers is detected.
*
* @method patch
* @public
* @param {Operation} op the operation to perform
* @returns {void}
*/
patch(op: MergeOperation): void {
if (LOG_OPERATIONS) {
try {
let _data = JSON.parse(JSON.stringify(op));
// eslint-disable-next-line no-console
console.log(`EmberData | Operation - patch ${op.op}`, _data);
} catch (e) {
// eslint-disable-next-line no-console
console.log(`EmberData | Operation - patch ${op.op}`, op);
}
}
if (op.op === 'mergeIdentifiers') {
const cache = this.__cache.get(op.record);
if (cache) {
this.__cache.set(op.value, cache);
this.__cache.delete(op.record);
}
this.__graph.update(op, true);
}
}
/**
* Update the "local" or "current" (unpersisted) state of the Cache
*
* @method mutate
* @param {Mutation} mutation
* @returns {void}
* @public
*/
mutate(mutation: LocalRelationshipOperation): void {
if (LOG_MUTATIONS) {
try {
let _data = JSON.parse(JSON.stringify(mutation));
// eslint-disable-next-line no-console
console.log(`EmberData | Mutation - update ${mutation.op}`, _data);
} catch (e) {
// eslint-disable-next-line no-console
console.log(`EmberData | Mutation - update ${mutation.op}`, mutation);
}
}
this.__graph.update(mutation, false);
}
/**
* Peek resource data from the Cache.
*
* In development, if the return value
* is JSON the return value
* will be deep-cloned and deep-frozen
* to prevent mutation thereby enforcing cache
* Immutability.
*
* This form of peek is useful for implementations
* that want to feed raw-data from cache to the UI
* or which want to interact with a blob of data
* directly from the presentation cache.
*
* An implementation might want to do this because
* de-referencing records which read from their own
* blob is generally safer because the record does
* not require retainining connections to the Store
* and Cache to present data on a per-field basis.
*
* This generally takes the place of `getAttr` as
* an API and may even take the place of `getRelationship`
* depending on implementation specifics, though this
* latter usage is less recommended due to the advantages
* of the Graph handling necessary entanglements and
* notifications for relational data.
*
* @method peek
* @public
* @param {StableRecordIdentifier | StableDocumentIdentifier} identifier
* @returns {ResourceDocument | ResourceBlob | null} the known resource data
*/
peek(identifier: StableRecordIdentifier): ResourceBlob | null;
peek(identifier: StableDocumentIdentifier): ResourceDocument | null;
peek(identifier: StableDocumentIdentifier | StableRecordIdentifier): ResourceBlob | ResourceDocument | null {
if ('type' in identifier) {
const peeked = this.__safePeek(identifier, false);
if (!peeked) {
return null;
}
const { type, id, lid } = identifier;
const attributes = Object.assign({}, peeked.remoteAttrs, peeked.inflightAttrs, peeked.localAttrs);
const relationships = {};
const rels = this.__graph.identifiers.get(identifier);
if (rels) {
Object.keys(rels).forEach((key) => {
const rel = rels[key]!;
if (rel.definition.isImplicit) {
return;
} else {
relationships[key] = this.__graph.getData(identifier, key);
}
});
}
return {
type,
id,
lid,
attributes,
relationships,
};
}
const document = this.peekRequest(identifier);
if (document) {
if ('content' in document) return document.content;
}
return null;
}
/**
* Peek the Cache for the existing request data associated with
* a cacheable request
*
* @method peekRequest
* @param {StableDocumentIdentifier}
* @returns {StableDocumentIdentifier | null}
* @public
*/
peekRequest(identifier: StableDocumentIdentifier): StructuredDocument<ResourceDocument> | null {
return this.__documents.get(identifier.lid) || null;
}
/**
* Push resource data from a remote source into the cache for this identifier
*
* @method upsert
* @public
* @param identifier
* @param data
* @param hasRecord
* @returns {void | string[]} if `hasRecord` is true then calculated key changes should be returned
*/
upsert(
identifier: StableRecordIdentifier,
data: JsonApiResource,
calculateChanges?: boolean | undefined
): void | string[] {
let changedKeys: string[] | undefined;
const peeked = this.__safePeek(identifier, false);
const existed = !!peeked;
const cached = peeked || this._createCache(identifier);
const isLoading = /*#__NOINLINE__*/ _isLoading(peeked, this.__storeWrapper, identifier) || !recordIsLoaded(peeked);
let isUpdate = /*#__NOINLINE__*/ !_isEmpty(peeked) && !isLoading;
if (LOG_OPERATIONS) {
try {
let _data = JSON.parse(JSON.stringify(data));
// eslint-disable-next-line no-console
console.log(`EmberData | Operation - upsert (${existed ? 'merge' : 'insert'})`, _data);
} catch (e) {
// eslint-disable-next-line no-console
console.log(`EmberData | Operation - upsert (${existed ? 'merge' : 'insert'})`, data);
}
}
if (cached.isNew) {
cached.isNew = false;
this.__storeWrapper.notifyChange(identifier, 'identity');
this.__storeWrapper.notifyChange(identifier, 'state');
}
if (calculateChanges) {
changedKeys = existed ? calculateChangedKeys(cached, data.attributes) : Object.keys(data.attributes || {});
}
cached.remoteAttrs = Object.assign(cached.remoteAttrs || Object.create(null), data.attributes);
if (cached.localAttrs) {
if (patchLocalAttributes(cached)) {
this.__storeWrapper.notifyChange(identifier, 'state');
}
}
if (!isUpdate) {
this.__storeWrapper.notifyChange(identifier, 'added');
}
if (data.id) {
cached.id = data.id;
}
if (data.relationships) {
setupRelationships(this.__graph, this.__storeWrapper, identifier, data);
}
if (changedKeys && changedKeys.length) {
notifyAttributes(this.__storeWrapper, identifier, changedKeys);
}
return changedKeys;
}
// Cache Forking Support
// =====================
/**
* Create a fork of the cache from the current state.
*
* Applications should typically not call this method themselves,
* preferring instead to fork at the Store level, which will
* utilize this method to fork the cache.
*
* @method fork
* @internal
* @returns Promise<Cache>
*/
fork(): Promise<Cache> {
throw new Error(`Not Implemented`);
}
/**
* Merge a fork back into a parent Cache.
*
* Applications should typically not call this method themselves,
* preferring instead to merge at the Store level, which will
* utilize this method to merge the caches.
*
* @method merge
* @param {Cache} cache
* @public
* @returns Promise<void>
*/
merge(cache: Cache): Promise<void> {
throw new Error(`Not Implemented`);
}
/**
* Generate the list of changes applied to all
* record in the store.
*
* Each individual resource or document that has
* been mutated should be described as an individual
* `Change` entry in the returned array.
*
* A `Change` is described by an object containing up to
* three properties: (1) the `identifier` of the entity that
* changed; (2) the `op` code of that change being one of
* `upsert` or `remove`, and if the op is `upsert` a `patch`
* containing the data to merge into the cache for the given
* entity.
*
* This `patch` is opaque to the Store but should be understood
* by the Cache and may expect to be utilized by an Adapter
* when generating data during a `save` operation.
*
* It is generally recommended that the `patch` contain only
* the updated state, ignoring fields that are unchanged
*
* ```ts
* interface Change {
* identifier: StableRecordIdentifier | StableDocumentIdentifier;
* op: 'upsert' | 'remove';
* patch?: unknown;
* }
* ```
*
* @method diff
* @public
*/
diff(): Promise<Change[]> {
throw new Error(`Not Implemented`);
}
// SSR Support
// ===========
/**
* Serialize the entire contents of the Cache into a Stream
* which may be fed back into a new instance of the same Cache
* via `cache.hydrate`.
*
* @method dump
* @returns {Promise<ReadableStream>}
* @public
*/
dump(): Promise<ReadableStream<unknown>> {
throw new Error(`Not Implemented`);
}
/**
* hydrate a Cache from a Stream with content previously serialized
* from another instance of the same Cache, resolving when hydration
* is complete.
*
* This method should expect to be called both in the context of restoring
* the Cache during application rehydration after SSR **AND** at unknown
* times during the lifetime of an already booted application when it is
* desired to bulk-load additional information into the cache. This latter
* behavior supports optimizing pre/fetching of data for route transitions
* via data-only SSR modes.
*
* @method hydrate
* @param {ReadableStream} stream
* @returns {Promise<void>}
* @public
*/
hydrate(stream: ReadableStream<unknown>): Promise<void> {
throw new Error('Not Implemented');
}
// Resource Support
// ================
/**
* [LIFECYCLE] Signal to the cache that a new record has been instantiated on the client
*
* It returns properties from options that should be set on the record during the create
* process. This return value behavior is deprecated.
*
* @method clientDidCreate
* @public
* @param identifier
* @param createArgs
*/
clientDidCreate(
identifier: StableRecordIdentifier,
options?: Record<string, unknown> | undefined
): Record<string, unknown> {
if (LOG_MUTATIONS) {
try {
let _data = options ? JSON.parse(JSON.stringify(options)) : options;
// eslint-disable-next-line no-console
console.log(`EmberData | Mutation - clientDidCreate ${identifier.lid}`, _data);
} catch (e) {
// eslint-disable-next-line no-console
console.log(`EmberData | Mutation - clientDidCreate ${identifier.lid}`, options);
}
}
const cached = this._createCache(identifier);
cached.isNew = true;
let createOptions = {};
if (options !== undefined) {
const storeWrapper = this.__storeWrapper;
let attributeDefs = storeWrapper.getSchemaDefinitionService().attributesDefinitionFor(identifier);
let relationshipDefs = storeWrapper.getSchemaDefinitionService().relationshipsDefinitionFor(identifier);
const graph = this.__graph;
let propertyNames = Object.keys(options);
for (let i = 0; i < propertyNames.length; i++) {
let name = propertyNames[i];
let propertyValue = options[name];
if (name === 'id') {
continue;
}
const fieldType: AttributeSchema | RelationshipSchema | undefined =
relationshipDefs[name] || attributeDefs[name];
let kind = fieldType !== undefined ? ('kind' in fieldType ? fieldType.kind : 'attribute') : null;
let relationship;
switch (kind) {
case 'attribute':
this.setAttr(identifier, name, propertyValue);
break;
case 'belongsTo':
this.mutate({
op: 'replaceRelatedRecord',
field: name,
record: identifier,
value: propertyValue as StableRecordIdentifier | null,
});
relationship = graph.get(identifier, name);
relationship.state.hasReceivedData = true;
relationship.state.isEmpty = false;
break;
case 'hasMany':
this.mutate({
op: 'replaceRelatedRecords',
field: name,
record: identifier,
value: propertyValue as StableRecordIdentifier[],
});
relationship = graph.get(identifier, name);
relationship.state.hasReceivedData = true;
relationship.state.isEmpty = false;
break;
default:
// reflect back (pass-thru) unknown properties
createOptions[name] = propertyValue;
}
}
}
this.__storeWrapper.notifyChange(identifier, 'added');
return createOptions;
}
/**
* [LIFECYCLE] Signals to the cache that a resource
* will be part of a save transaction.
*
* @method willCommit
* @public
* @param identifier
*/
willCommit(identifier: StableRecordIdentifier): void {
const cached = this.__peek(identifier, false);
cached.inflightAttrs = cached.localAttrs;
cached.localAttrs = null;
if (DEBUG) {
if (!DEPRECATE_RELATIONSHIP_REMOTE_UPDATE_CLEARING_LOCAL_STATE) {
// save off info about saved relationships
const relationships = this.__storeWrapper.getSchemaDefinitionService().relationshipsDefinitionFor(identifier);
Object.keys(relationships).forEach((relationshipName) => {
const relationship = relationships[relationshipName];
if (relationship.kind === 'belongsTo') {
if (this.__graph._isDirty(identifier, relationshipName)) {
const relationshipData = this.__graph.getData(identifier, relationshipName);
// @ts-expect-error debugging only property
const inFlight = (cached.inflightRelationships = cached.inflightRelationships || Object.create(null));
inFlight[relationshipName] = relationshipData;
}
}
});
}
}
}
/**
* [LIFECYCLE] Signals to the cache that a resource
* was successfully updated as part of a save transaction.
*
* @method didCommit
* @public
* @param identifier
* @param data
*/
didCommit(
committedIdentifier: StableRecordIdentifier,
result: StructuredDataDocument<SingleResourceDocument>
): SingleResourceDataDocument {
const payload = result.content;
const operation = result.request!.op;
const data = payload && payload.data;
if (!data) {
assert(
`Your ${committedIdentifier.type} record was saved to the server, but the response does not have an id and no id has been set client side. Records must have ids. Please update the server response to provide an id in the response or generate the id on the client side either before saving the record or while normalizing the response.`,
committedIdentifier.id
);
}
const { identifierCache } = this.__storeWrapper;
const existingId = committedIdentifier.id;
const identifier: StableRecordIdentifier =
operation !== 'deleteRecord' && data
? identifierCache.updateRecordIdentifier(committedIdentifier, data)
: committedIdentifier;
const cached = this.__peek(identifier, false);
if (cached.isDeleted) {
this.__graph.push({
op: 'deleteRecord',
record: identifier,
isNew: false,
});
cached.isDeletionCommitted = true;
this.__storeWrapper.notifyChange(identifier, 'removed');
// TODO @runspired should we early exit here?
}
if (DEBUG) {
if (cached.isNew && !identifier.id && (typeof data?.id !== 'string' || data.id.length > 0)) {
const error = new Error(`Expected an id ${String(identifier)} in response ${JSON.stringify(data)}`);
//@ts-expect-error
error.isAdapterError = true;
//@ts-expect-error
error.code = 'InvalidError';
throw error;
}
}
cached.isNew = false;
let newCanonicalAttributes: AttributesHash | undefined;
if (data) {
if (data.id && !cached.id) {
cached.id = data.id;
}
if (identifier === committedIdentifier && identifier.id !== existingId) {
this.__storeWrapper.notifyChange(identifier, 'identity');
}
assert(
`Expected the ID received for the primary '${identifier.type}' resource being saved to match the current id '${cached.id}' but received '${identifier.id}'.`,
identifier.id === cached.id
);
if (data.relationships) {
if (DEBUG) {
if (!DEPRECATE_RELATIONSHIP_REMOTE_UPDATE_CLEARING_LOCAL_STATE) {
// assert against bad API behavior where a belongsTo relationship
// is saved but the return payload indicates a different final state.
const relationships = this.__storeWrapper
.getSchemaDefinitionService()
.relationshipsDefinitionFor(identifier);
Object.keys(relationships).forEach((relationshipName) => {
const relationship = relationships[relationshipName];
if (relationship.kind === 'belongsTo') {
const relationshipData = data.relationships![relationshipName]?.data;
if (relationshipData !== undefined) {
// @ts-expect-error debugging only property
const inFlightData = cached.inflightRelationships?.[relationshipName] as ResourceRelationship;
if (!inFlightData || !('data' in inFlightData)) {
return;
}
const actualData = relationshipData
? this.__storeWrapper.identifierCache.getOrCreateRecordIdentifier(relationshipData)
: null;
assert(
`Expected the resource relationship '<${identifier.type}>.${relationshipName}' on ${
identifier.lid
} to be saved as ${inFlightData.data ? inFlightData.data.lid : '<null>'} but it was saved as ${
actualData ? actualData.lid : '<null>'
}`,
inFlightData.data === actualData
);
}
}
});
// @ts-expect-error debugging only property
cached.inflightRelationships = undefined;
}
}
setupRelationships(this.__graph, this.__storeWrapper, identifier, data);
}
newCanonicalAttributes = data.attributes;
}
let changedKeys = calculateChangedKeys(cached, newCanonicalAttributes);
cached.remoteAttrs = Object.assign(
cached.remoteAttrs || Object.create(null),
cached.inflightAttrs,
newCanonicalAttributes
);
cached.inflightAttrs = null;
patchLocalAttributes(cached);
if (cached.errors) {
cached.errors = null;
this.__storeWrapper.notifyChange(identifier, 'errors');
}
notifyAttributes(this.__storeWrapper, identifier, changedKeys);
this.__storeWrapper.notifyChange(identifier, 'state');
const included = payload && payload.included;
if (included) {
for (let i = 0, length = included.length; i < length; i++) {
putOne(this, identifierCache, included[i]);
}
}
return {
data: identifier as StableExistingRecordIdentifier,
};
}
/**
* [LIFECYCLE] Signals to the cache that a resource
* was update via a save transaction failed.
*
* @method commitWasRejected
* @public
* @param identifier
* @param errors
*/
commitWasRejected(identifier: StableRecordIdentifier, errors?: JsonApiError[] | undefined): void {
const cached = this.__peek(identifier, false);
if (cached.inflightAttrs) {
let keys = Object.keys(cached.inflightAttrs);
if (keys.length > 0) {
let attrs = (cached.localAttrs = cached.localAttrs || Object.create(null));
for (let i = 0; i < keys.length; i++) {
if (attrs[keys[i]] === undefined) {
attrs[keys[i]] = cached.inflightAttrs[keys[i]];
}
}
}
cached.inflightAttrs = null;
}
if (errors) {
cached.errors = errors;
}
this.__storeWrapper.notifyChange(identifier, 'errors');
}
/**
* [LIFECYCLE] Signals to the cache that all data for a resource
* should be cleared.
*
* This method is a candidate to become a mutation
*
* @method unloadRecord
* @public
* @param identifier
*/
unloadRecord(identifier: StableRecordIdentifier): void {
const storeWrapper = this.__storeWrapper;
// TODO this is necessary because
// we maintain memebership inside InstanceCache
// for peekAll, so even though we haven't created
// any data we think this exists.
// TODO can we eliminate that membership now?
if (!this.__cache.has(identifier)) {
// the graph may still need to unload identity
peekGraph(storeWrapper)?.unload(identifier);
return;
}
const removeFromRecordArray = !this.isDeletionCommitted(identifier);
let removed = false;
const cached = this.__peek(identifier, false);
if (cached.isNew) {
peekGraph(storeWrapper)?.push({
op: 'deleteRecord',
record: identifier,
isNew: true,
});
} else {
peekGraph(storeWrapper)?.unload(identifier);
}
// effectively clearing these is ensuring that
// we report as `isEmpty` during teardown.
cached.localAttrs = null;
cached.remoteAttrs = null;
cached.inflightAttrs = null;
let relatedIdentifiers = _allRelatedIdentifiers(storeWrapper, identifier);
if (areAllModelsUnloaded(storeWrapper, relatedIdentifiers)) {
for (let i = 0; i < relatedIdentifiers.length; ++i) {
let relatedIdentifier = relatedIdentifiers[i];
storeWrapper.notifyChange(relatedIdentifier, 'removed');
removed = true;
storeWrapper.disconnectRecord(relatedIdentifier);
}
}
this.__cache.delete(identifier);
this.__destroyedCache.set(identifier, cached);
/*
* The destroy cache is a hack to prevent applications
* from blowing up during teardown. Accessing state
* on a destroyed record is not safe, but historically
* was possible due to a combination of teardown timing
* and retention of cached state directly on the
* record itself.
*
* Once we have deprecated accessing state on a destroyed
* instance we may remove this. The timing isn't a huge deal
* as momentarily retaining the objects outside the bounds
* of a test won't cause issues.
*/
if (this.__destroyedCache.size === 1) {
// TODO do we still need this?
setTimeout(() => {
this.__destroyedCache.clear();