-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathcache.ts
2208 lines (1970 loc) · 70.7 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 type { CollectionEdge, Graph, GraphEdge, ImplicitEdge, ResourceEdge } from '@ember-data/graph/-private';
import { graphFor, isBelongsTo, peekGraph } from '@ember-data/graph/-private';
import type Store from '@ember-data/store';
import { isStableIdentifier, logGroup } from '@ember-data/store/-private';
import type { CacheCapabilitiesManager } from '@ember-data/store/types';
import { LOG_MUTATIONS, LOG_OPERATIONS, LOG_REQUESTS } from '@warp-drive/build-config/debugging';
import { DEPRECATE_RELATIONSHIP_REMOTE_UPDATE_CLEARING_LOCAL_STATE } from '@warp-drive/build-config/deprecations';
import { DEBUG } from '@warp-drive/build-config/env';
import { assert } from '@warp-drive/build-config/macros';
import type { Cache, ChangedAttributesHash, RelationshipDiff } from '@warp-drive/core-types/cache';
import type { Change } from '@warp-drive/core-types/cache/change';
import type { MergeOperation } from '@warp-drive/core-types/cache/operations';
import type { CollectionRelationship, ResourceRelationship } from '@warp-drive/core-types/cache/relationship';
import type { LocalRelationshipOperation } from '@warp-drive/core-types/graph';
import type {
StableDocumentIdentifier,
StableExistingRecordIdentifier,
StableRecordIdentifier,
} from '@warp-drive/core-types/identifier';
import type { ObjectValue, Value } from '@warp-drive/core-types/json/raw';
import type {
ImmutableRequestInfo,
StructuredDataDocument,
StructuredDocument,
StructuredErrorDocument,
} from '@warp-drive/core-types/request';
import type {
CollectionField,
FieldSchema,
LegacyHasManyField,
LegacyRelationshipSchema,
ResourceField,
} from '@warp-drive/core-types/schema/fields';
import type {
CollectionResourceDataDocument,
ResourceDataDocument,
ResourceDocument,
ResourceErrorDocument,
ResourceMetaDocument,
SingleResourceDataDocument,
} from '@warp-drive/core-types/spec/document';
import type { ApiError } from '@warp-drive/core-types/spec/error';
import type {
CollectionResourceDocument,
ExistingResourceObject,
ResourceObject,
SingleResourceDocument,
SingleResourceRelationship,
} from '@warp-drive/core-types/spec/json-api-raw';
import { validateDocumentFields } from './validate-document-fields';
type IdentifierCache = Store['identifierCache'];
type InternalCapabilitiesManager = CacheCapabilitiesManager & { _store: Store };
function isImplicit(relationship: GraphEdge): relationship is ImplicitEdge {
return relationship.definition.isImplicit;
}
function upgradeCapabilities(obj: unknown): asserts obj is InternalCapabilitiesManager {}
const EMPTY_ITERATOR = {
iterator() {
return {
next() {
return { done: true, value: undefined };
},
};
},
};
interface CachedResource {
id: string | null;
remoteAttrs: Record<string, Value | undefined> | null;
localAttrs: Record<string, Value | undefined> | null;
defaultAttrs: Record<string, Value | undefined> | null;
inflightAttrs: Record<string, Value | undefined> | null;
changes: Record<string, [Value | undefined, Value]> | null;
errors: ApiError[] | null;
isNew: boolean;
isDeleted: boolean;
isDeletionCommitted: boolean;
/**
* debugging only
*
* @internal
*/
inflightRelationships?: Record<string, unknown> | null;
}
function makeCache(): CachedResource {
return {
id: null,
remoteAttrs: null,
localAttrs: null,
defaultAttrs: 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 _capabilities: CacheCapabilitiesManager;
declare __cache: Map<StableRecordIdentifier, CachedResource>;
declare __destroyedCache: Map<StableRecordIdentifier, CachedResource>;
declare __documents: Map<string, StructuredDocument<ResourceDocument>>;
declare __graph: Graph;
constructor(capabilities: CacheCapabilitiesManager) {
this.version = '2';
this._capabilities = capabilities;
this.__cache = new Map();
this.__graph = graphFor(capabilities);
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
* @return {ResourceDocument}
* @public
*/
put<T extends SingleResourceDocument>(doc: StructuredDataDocument<T>): SingleResourceDataDocument;
put<T extends CollectionResourceDocument>(doc: StructuredDataDocument<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 ${typeof doc.content}`,
doc instanceof Error || (typeof doc.content === 'object' && doc.content !== null)
);
if (isErrorDocument(doc)) {
return this._putDocument(doc, undefined, undefined);
} else if (isMetaDocument(doc)) {
return this._putDocument(doc, undefined, undefined);
}
const jsonApiDoc = doc.content as SingleResourceDocument | CollectionResourceDocument;
const included = jsonApiDoc.included;
let i: number, length: number;
const { identifierCache } = this._capabilities;
if (DEBUG) {
validateDocumentFields(this._capabilities.schema, jsonApiDoc);
}
if (LOG_REQUESTS) {
const Counts = new Map();
let totalCount = 0;
if (included) {
for (i = 0, length = included.length; i < length; i++) {
const type = included[i].type;
Counts.set(type, (Counts.get(type) || 0) + 1);
totalCount++;
}
}
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);
totalCount++;
}
} else if (jsonApiDoc.data) {
const type = jsonApiDoc.data.type;
Counts.set(type, (Counts.get(type) || 0) + 1);
totalCount++;
}
logGroup(
'cache',
'put',
'<@document>',
doc.content?.lid || doc.request?.url || 'unknown-request',
`(${totalCount}) records`,
''
);
let str = `\tContent Counts:`;
Counts.forEach((count, type) => {
str += `\n\t\t${type}: ${count} record${count > 1 ? 's' : ''}`;
});
if (Counts.size === 0) {
str += `\t(empty)`;
}
// eslint-disable-next-line no-console
console.log(str);
// eslint-disable-next-line no-console
console.log({
lid: doc.content?.lid,
content: structuredClone(doc.content),
// we may need a specialized copy here
request: doc.request, // structuredClone(doc.request),
response: doc.response, // structuredClone(doc.response),
});
// eslint-disable-next-line no-console
console.groupEnd();
}
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;
const 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[]
);
}
const 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 ResourceDataDocument).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 ResourceDataDocument).included = included;
}
const request = doc.request as ImmutableRequestInfo | undefined;
const identifier = request ? this._capabilities.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._capabilities.notifyChange(identifier, hasExisting ? 'updated' : 'added', null);
}
if (doc.request?.op === 'findHasMany') {
const parentIdentifier = doc.request.options?.identifier as StableRecordIdentifier | undefined;
const parentField = doc.request.options?.field as LegacyHasManyField | undefined;
assert(`Expected a hasMany field`, parentField?.kind === 'hasMany');
assert(
`Expected a parent identifier for a findHasMany request`,
parentIdentifier && isStableIdentifier(parentIdentifier)
);
if (parentField && parentIdentifier) {
this.__graph.push({
op: 'updateRelationship',
record: parentIdentifier,
field: parentField.name,
value: resourceDocument,
});
}
}
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
* @return {void}
*/
patch(op: MergeOperation): void {
if (LOG_OPERATIONS) {
try {
const _data = JSON.parse(JSON.stringify(op)) as object;
// eslint-disable-next-line no-console
console.log(`EmberData | Operation - patch ${op.op}`, _data);
} catch {
// 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
* @return {void}
* @public
*/
mutate(mutation: LocalRelationshipOperation): void {
if (LOG_MUTATIONS) {
logGroup('cache', 'mutate', mutation.record.type, mutation.record.lid, mutation.field, mutation.op);
try {
const _data = JSON.parse(JSON.stringify(mutation)) as object;
// eslint-disable-next-line no-console
console.log(_data);
} catch {
// eslint-disable-next-line no-console
console.log(mutation);
}
}
this.__graph.update(mutation, false);
if (LOG_MUTATIONS) {
// eslint-disable-next-line no-console
console.groupEnd();
}
}
/**
* 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
* @return {ResourceDocument | ResourceObject | null} the known resource data
*/
peek(identifier: StableRecordIdentifier): ResourceObject | null;
peek(identifier: StableDocumentIdentifier): ResourceDocument | null;
peek(identifier: StableDocumentIdentifier | StableRecordIdentifier): ResourceObject | 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) as ObjectValue;
const relationships: ResourceObject['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);
}
});
}
upgradeCapabilities(this._capabilities);
const store = this._capabilities._store;
const attrs = this._capabilities.schema.fields(identifier);
attrs.forEach((attr, key) => {
if (key in attributes && attributes[key] !== undefined) {
return;
}
const defaultValue = getDefaultValue(attr, identifier, store);
if (defaultValue !== undefined) {
attributes[key] = defaultValue;
}
});
return {
type,
id,
lid,
attributes,
relationships,
};
}
const document = this.peekRequest(identifier);
if (document) {
if ('content' in document) return document.content!;
}
return null;
}
peekRemoteState(identifier: StableRecordIdentifier): ResourceObject | null;
peekRemoteState(identifier: StableDocumentIdentifier): ResourceDocument | null;
peekRemoteState(
identifier: StableDocumentIdentifier | StableRecordIdentifier
): ResourceObject | 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) as ObjectValue;
const relationships: ResourceObject['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);
}
});
}
upgradeCapabilities(this._capabilities);
const store = this._capabilities._store;
const attrs = this._capabilities.schema.fields(identifier);
attrs.forEach((attr, key) => {
if (key in attributes && attributes[key] !== undefined) {
return;
}
const defaultValue = getDefaultValue(attr, identifier, store);
if (defaultValue !== undefined) {
attributes[key] = defaultValue;
}
});
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.
*
* This is effectively the reverse of `put` for a request in
* that it will return the the request, response, and content
* whereas `peek` will return just the `content`.
*
* @method peekRequest
* @param {StableDocumentIdentifier}
* @return {StructuredDocument<ResourceDocument> | 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
* @return {void | string[]} if `hasRecord` is true then calculated key changes should be returned
*/
upsert(
identifier: StableRecordIdentifier,
data: ExistingResourceObject,
calculateChanges?: boolean
): void | string[] {
let changedKeys: Set<string> | undefined;
const peeked = this.__safePeek(identifier, false);
const existed = !!peeked;
const cached = peeked || this._createCache(identifier);
const isLoading = /*#__NOINLINE__*/ _isLoading(peeked, this._capabilities, identifier) || !recordIsLoaded(peeked);
const isUpdate = /*#__NOINLINE__*/ !_isEmpty(peeked) && !isLoading;
if (LOG_OPERATIONS) {
logGroup(
'cache',
'upsert',
identifier.type,
identifier.lid,
existed ? 'merged' : 'inserted',
calculateChanges ? 'has-subscription' : ''
);
try {
const _data = JSON.parse(JSON.stringify(data)) as object;
// eslint-disable-next-line no-console
console.log(_data);
} catch {
// eslint-disable-next-line no-console
console.log(data);
}
}
if (cached.isNew) {
cached.isNew = false;
this._capabilities.notifyChange(identifier, 'identity', null);
this._capabilities.notifyChange(identifier, 'state', null);
}
const fields = this._capabilities.schema.fields(identifier);
// if no cache entry existed, no record exists / property has been accessed
// and thus we do not need to notify changes to any properties.
if (calculateChanges && existed && data.attributes) {
changedKeys = calculateChangedKeys(cached, data.attributes, fields);
}
cached.remoteAttrs = Object.assign(
cached.remoteAttrs || (Object.create(null) as Record<string, unknown>),
data.attributes
);
if (cached.localAttrs) {
if (patchLocalAttributes(cached, changedKeys)) {
this._capabilities.notifyChange(identifier, 'state', null);
}
}
if (!isUpdate) {
this._capabilities.notifyChange(identifier, 'added', null);
}
if (data.id) {
cached.id = data.id;
}
if (data.relationships) {
setupRelationships(this.__graph, fields, identifier, data);
}
if (changedKeys?.size) {
notifyAttributes(this._capabilities, identifier, changedKeys);
}
if (LOG_OPERATIONS) {
// eslint-disable-next-line no-console
console.groupEnd();
}
return changedKeys?.size ? Array.from(changedKeys) : undefined;
}
// 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
* @return 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
* @return 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
* @return {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
* @return {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, Value>): Record<string, unknown> {
if (LOG_MUTATIONS) {
try {
const _data = options ? (JSON.parse(JSON.stringify(options)) as object) : options;
// eslint-disable-next-line no-console
console.log(`EmberData | Mutation - clientDidCreate ${identifier.lid}`, _data);
} catch {
// eslint-disable-next-line no-console
console.log(`EmberData | Mutation - clientDidCreate ${identifier.lid}`, options);
}
}
const cached = this._createCache(identifier);
cached.isNew = true;
const createOptions: Record<string, unknown> = {};
if (options !== undefined) {
const storeWrapper = this._capabilities;
const fields = storeWrapper.schema.fields(identifier);
const graph = this.__graph;
const propertyNames = Object.keys(options);
for (let i = 0; i < propertyNames.length; i++) {
const name = propertyNames[i];
const propertyValue = options[name];
if (name === 'id') {
continue;
}
const fieldType: FieldSchema | undefined = fields.get(name);
const kind = fieldType !== undefined ? ('kind' in fieldType ? fieldType.kind : 'attribute') : null;
let relationship: ResourceEdge | CollectionEdge;
switch (kind) {
case 'attribute':
this.setAttr(identifier, name, propertyValue);
createOptions[name] = propertyValue;
break;
case 'belongsTo':
this.mutate({
op: 'replaceRelatedRecord',
field: name,
record: identifier,
value: propertyValue as StableRecordIdentifier | null,
});
relationship = graph.get(identifier, name) as ResourceEdge;
relationship.state.hasReceivedData = true;
relationship.state.isEmpty = false;
break;
case 'hasMany':
this.mutate({
op: 'replaceRelatedRecords',
field: name,
record: identifier,
value: propertyValue as unknown as StableRecordIdentifier[],
});
relationship = graph.get(identifier, name) as CollectionEdge;
relationship.state.hasReceivedData = true;
relationship.state.isEmpty = false;
break;
default:
// reflect back (pass-thru) unknown properties
createOptions[name] = propertyValue;
}
}
}
this._capabilities.notifyChange(identifier, 'added', null);
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);
/*
if we have multiple saves in flight at once then
we have information loss no matter what. This
attempts to lose the least information.
If we were to clear inflightAttrs, previous requests
would not be able to use it during their didCommit.
If we upsert inflightattrs, previous requests incorrectly
see more recent inflight changes as part of their own and
will incorrectly mark the new state as the correct remote state.
We choose this latter behavior to avoid accidentally removing
earlier changes.
If apps do not want this behavior they can either
- chain save requests serially vs allowing concurrent saves
- move to using a request handler that caches the inflight state
on a per-request basis
- change their save requests to only send a "PATCH" instead of a "PUT"
so that only latest changes are involved in each request, and then also
ensure that the API or their handler reflects only those changes back
for upsert into the cache.
*/
if (cached.inflightAttrs) {
if (cached.localAttrs) {
Object.assign(cached.inflightAttrs, cached.localAttrs);
}
} else {
cached.inflightAttrs = cached.localAttrs;
}
cached.localAttrs = null;
if (DEBUG) {
if (!DEPRECATE_RELATIONSHIP_REMOTE_UPDATE_CLEARING_LOCAL_STATE) {
// save off info about saved relationships
const fields = this._capabilities.schema.fields(identifier);
fields.forEach((schema, name) => {
if (schema.kind === 'belongsTo') {
if (this.__graph._isDirty(identifier, name)) {
const relationshipData = this.__graph.getData(identifier, name);
const inFlight = (cached.inflightRelationships =
cached.inflightRelationships || (Object.create(null) as Record<string, unknown>));
inFlight[name] = 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._capabilities;
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._capabilities.notifyChange(identifier, 'removed', null);
// TODO @runspired should we early exit here?
}