-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
store-service.ts
2502 lines (2112 loc) · 76.3 KB
/
store-service.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/store
*/
// this import location is deprecated but breaks in 4.8 and older
import { getOwner } from '@ember/application';
import { assert } from '@ember/debug';
import EmberObject from '@ember/object';
import type { Object as JSONObject } from 'json-typescript';
import { LOG_PAYLOADS, LOG_REQUESTS } from '@ember-data/debugging';
import { DEBUG, TESTING } from '@ember-data/env';
import type { Graph } from '@ember-data/graph/-private/graph';
import type { FetchManager } from '@ember-data/legacy-compat/-private';
import type RequestManager from '@ember-data/request';
import type { Future } from '@ember-data/request/-private/types';
import { ResourceDocument } from '@ember-data/types/cache/document';
import { StableDocumentIdentifier } from '@ember-data/types/cache/identifier';
import type { Cache, CacheV1 } from '@ember-data/types/q/cache';
import type { CacheCapabilitiesManager } from '@ember-data/types/q/cache-store-wrapper';
import { ModelSchema } from '@ember-data/types/q/ds-model';
import type {
CollectionResourceDocument,
EmptyResourceDocument,
JsonApiDocument,
ResourceIdentifierObject,
SingleResourceDocument,
} from '@ember-data/types/q/ember-data-json-api';
import type { StableExistingRecordIdentifier, StableRecordIdentifier } from '@ember-data/types/q/identifier';
import type { MinimumAdapterInterface } from '@ember-data/types/q/minimum-adapter-interface';
import type { MinimumSerializerInterface } from '@ember-data/types/q/minimum-serializer-interface';
import type { RecordInstance } from '@ember-data/types/q/record-instance';
import type { SchemaService } from '@ember-data/types/q/schema-service';
import type { FindOptions } from '@ember-data/types/q/store';
import {
EnableHydration,
type LifetimesService,
SkipCache,
StoreRequestContext,
type StoreRequestInput,
} from './cache-handler';
import { IdentifierCache } from './caches/identifier-cache';
import {
InstanceCache,
peekRecordIdentifier,
preloadData,
recordIdentifierFor,
resourceIsFullyDeleted,
storeFor,
} from './caches/instance-cache';
import { Document } from './document';
import type RecordReference from './legacy-model-support/record-reference';
import { getShimClass } from './legacy-model-support/shim-model-class';
import { CacheManager } from './managers/cache-manager';
import NotificationManager from './managers/notification-manager';
import RecordArrayManager from './managers/record-array-manager';
import RequestStateService, { RequestPromise } from './network/request-cache';
import IdentifierArray, { Collection } from './record-arrays/identifier-array';
import coerceId, { ensureStringId } from './utils/coerce-id';
import constructResource from './utils/construct-resource';
import normalizeModelName from './utils/normalize-model-name';
export { storeFor };
export interface CreateRecordProperties {
id?: string | null;
[key: string]: unknown;
}
/**
* A Store coordinates interaction between your application, a [Cache](https://api.emberjs.com/ember-data/release/classes/%3CInterface%3E%20Cache),
* and sources of data (such as your API or a local persistence layer)
* accessed via a [RequestManager](https://github.com/emberjs/data/tree/main/packages/request).
*
* ```app/services/store.js
* import Store from '@ember-data/store';
*
* export default class extends Store {}
* ```
*
* Most Ember applications will only have a single `Store` configured as a Service
* in this manner. However, setting up multiple stores is possible, including using
* each as a unique service.
*
@class Store
@public
*/
// @ts-expect-error
interface Store {
createRecordDataFor?(identifier: StableRecordIdentifier, wrapper: CacheCapabilitiesManager): Cache | CacheV1;
createCache(storeWrapper: CacheCapabilitiesManager): Cache;
instantiateRecord(identifier: StableRecordIdentifier, createRecordArgs: { [key: string]: unknown }): RecordInstance;
teardownRecord(record: RecordInstance): void;
}
class Store extends EmberObject {
declare recordArrayManager: RecordArrayManager;
/**
* Provides access to the NotificationManager associated
* with this Store instance.
*
* The NotificationManager can be used to subscribe to
* changes to the cache.
*
* @property {NotificationManager} notifications
* @public
*/
declare notifications: NotificationManager;
/**
* Provides access to the SchemaService instance
* for this Store instance.
*
* The SchemaService can be used to query for
* information about the schema of a resource.
*
* @property {SchemaService} schema
* @public
*/
get schema(): SchemaService {
return this.getSchemaDefinitionService();
}
declare _schema: SchemaService;
/**
* Provides access to the IdentifierCache instance
* for this store.
*
* The IdentifierCache can be used to generate or
* retrieve a stable unique identifier for any resource.
*
* @property {IdentifierCache} identifierCache
* @public
*/
declare identifierCache: IdentifierCache;
/**
* Provides access to the requestManager instance associated
* with this Store instance.
*
* When using `ember-data` this property is automatically
* set to an instance of `RequestManager`. When not using `ember-data`
* you must configure this property yourself, either by declaring
* it as a service or by initializing it.
*
* ```ts
* import Store, { CacheHandler } from '@ember-data/store';
* import RequestManager from '@ember-data/request';
* import Fetch from '@ember/data/request/fetch';
*
* class extends Store {
* constructor() {
* super(...arguments);
* this.requestManager = new RequestManager();
* this.requestManager.use([Fetch]);
* this.requestManager.useCache(CacheHandler);
* }
* }
* ```
*
* @public
* @property {RequestManager} requestManager
*/
declare requestManager: RequestManager;
/**
* A Property which an App may set to provide a Lifetimes Service
* to control when a cached request becomes stale.
*
* Note, when defined, these methods will only be invoked if a
* cache key exists for the request, either because the request
* contains `cacheOptions.key` or because the [IdentifierCache](/ember-data/release/classes/IdentifierCache)
* was able to generate a key for the request using the configured
* [generation method](/ember-data/release/functions/@ember-data%2Fstore/setIdentifierGenerationMethod).
*
* `isSoftExpired` will only be invoked if `isHardExpired` returns `false`.
*
* ```ts
* store.lifetimes = {
* // make the request and ignore the current cache state
* isHardExpired(identifier: StableDocumentIdentifier): boolean {
* return false;
* }
*
* // make the request in the background if true, return cache state
* isSoftExpired(identifier: StableDocumentIdentifier): boolean {
* return false;
* }
* }
* ```
*
* @public
* @property {LivetimesService|undefined} lifetimes
*/
declare lifetimes?: LifetimesService;
// Private
declare _graph?: Graph;
declare _fetchManager: FetchManager;
declare _adapterCache: Record<string, MinimumAdapterInterface & { store: Store }>;
declare _serializerCache: Record<string, MinimumSerializerInterface & { store: Store }>;
declare _requestCache: RequestStateService;
declare _instanceCache: InstanceCache;
declare _documentCache: Map<StableDocumentIdentifier, Document<RecordInstance | RecordInstance[] | null | undefined>>;
declare _cbs: { coalesce?: () => void; sync?: () => void; notify?: () => void } | null;
declare _forceShim: boolean;
declare _enableAsyncFlush: boolean | null;
// DEBUG-only properties
declare DISABLE_WAITER?: boolean;
declare _isDestroying: boolean;
declare _isDestroyed: boolean;
get isDestroying(): boolean {
return this._isDestroying;
}
set isDestroying(value: boolean) {
this._isDestroying = value;
}
get isDestroyed(): boolean {
return this._isDestroyed;
}
set isDestroyed(value: boolean) {
this._isDestroyed = value;
}
/**
@method init
@private
*/
constructor(createArgs?: unknown) {
// @ts-expect-error ember-source types improperly expect createArgs to be `Owner`
super(createArgs);
Object.assign(this, createArgs);
this.identifierCache = new IdentifierCache();
this.notifications = new NotificationManager(this);
// private but maybe useful to be here, somewhat intimate
this.recordArrayManager = new RecordArrayManager({ store: this });
// private
this._requestCache = new RequestStateService(this);
this._instanceCache = new InstanceCache(this);
this._adapterCache = Object.create(null) as Record<string, MinimumAdapterInterface & { store: Store }>;
this._serializerCache = Object.create(null) as Record<string, MinimumSerializerInterface & { store: Store }>;
this._documentCache = new Map();
this.isDestroying = false;
this.isDestroyed = false;
}
_run(cb: () => void) {
assert(`EmberData should never encounter a nested run`, !this._cbs);
const _cbs: { coalesce?: () => void; sync?: () => void; notify?: () => void } = (this._cbs = {});
if (DEBUG) {
try {
cb();
if (_cbs.coalesce) {
_cbs.coalesce();
}
if (_cbs.sync) {
_cbs.sync();
}
if (_cbs.notify) {
_cbs.notify();
}
} finally {
this._cbs = null;
}
} else {
cb();
if (_cbs.coalesce) {
_cbs.coalesce();
}
if (_cbs.sync) {
_cbs.sync();
}
if (_cbs.notify) {
_cbs.notify();
}
this._cbs = null;
}
}
_join(cb: () => void): void {
if (this._cbs) {
cb();
} else {
this._run(cb);
}
}
_schedule(name: 'coalesce' | 'sync' | 'notify', cb: () => void): void {
assert(`EmberData expects to schedule only when there is an active run`, !!this._cbs);
assert(`EmberData expects only one flush per queue name, cannot schedule ${name}`, !this._cbs[name]);
this._cbs[name] = cb;
}
/**
* Retrieve the RequestStateService instance
* associated with this Store.
*
* This can be used to query the status of requests
* that have been initiated for a given identifier.
*
* @method getRequestStateService
* @returns {RequestStateService}
* @public
*/
getRequestStateService(): RequestStateService {
return this._requestCache;
}
_getAllPending(): (Promise<unknown[]> & { length: number }) | void {
if (TESTING) {
const all: Promise<unknown>[] = [];
const pending = this._requestCache._pending;
pending.forEach((requests) => {
all.push(...requests.map((v) => v[RequestPromise]!));
});
this.requestManager._pending.forEach((v) => all.push(v));
const promise: Promise<unknown[]> & { length: number } = Promise.allSettled(all) as Promise<unknown[]> & {
length: number;
};
promise.length = all.length;
return promise;
}
}
/**
* Issue a request via the configured RequestManager,
* inserting the response into the cache and handing
* back a Future which resolves to a ResponseDocument
*
* Resource data is always updated in the cache.
*
* Only GET requests have the request result and document
* cached by default when a cache key is present.
*
* The cache key used is `requestConfig.cacheOptions.key`
* if present, falling back to `requestconfig.url`.
*
* Params are not serialized as part of the cache-key, so
* either ensure they are already in the url or utilize
* `requestConfig.cacheOptions.key`. For queries issued
* via the `POST` method `requestConfig.cacheOptions.key`
* MUST be supplied for the document to be cached.
*
* @method request
* @param {StoreRequestInput} requestConfig
* @returns {Future}
* @public
*/
request<T>(requestConfig: StoreRequestInput): Future<T> {
// we lazily set the cache handler when we issue the first request
// because constructor doesn't allow for this to run after
// the user has had the chance to set the prop.
let opts: {
store: Store;
disableTestWaiter?: boolean;
[EnableHydration]: true;
records?: StableRecordIdentifier[];
} = {
store: this,
[EnableHydration]: true,
};
if (requestConfig.records) {
const identifierCache = this.identifierCache;
opts.records = requestConfig.records.map((r) => identifierCache.getOrCreateRecordIdentifier(r));
}
if (TESTING) {
if (this.DISABLE_WAITER) {
opts.disableTestWaiter =
typeof requestConfig.disableTestWaiter === 'boolean' ? requestConfig.disableTestWaiter : true;
}
}
if (LOG_REQUESTS) {
let options: unknown;
try {
options = JSON.parse(JSON.stringify(requestConfig));
} catch {
options = requestConfig;
}
// eslint-disable-next-line no-console
console.log(
`request: [[START]] ${requestConfig.op && !requestConfig.url ? '(LEGACY) ' : ''}${
requestConfig.op || '<unknown operation>'
} ${requestConfig.url || '<empty url>'} ${requestConfig.method || '<empty method>'}`,
options
);
}
const future = this.requestManager.request<T>(Object.assign(requestConfig, opts));
future.onFinalize(() => {
if (LOG_REQUESTS) {
// eslint-disable-next-line no-console
console.log(
`request: [[FINALIZE]] ${requestConfig.op && !requestConfig.url ? '(LEGACY) ' : ''}${
requestConfig.op || '<unknown operation>'
} ${requestConfig.url || '<empty url>'} ${requestConfig.method || '<empty method>'}`
);
}
// skip flush for legacy belongsTo
if (requestConfig.op === 'findBelongsTo' && !requestConfig.url) {
return;
}
this.notifications._flush();
});
return future;
}
/**
* A hook which an app or addon may implement. Called when
* the Store is attempting to create a Record Instance for
* a resource.
*
* This hook can be used to select or instantiate any desired
* mechanism of presentating cache data to the ui for access
* mutation, and interaction.
*
* @method instantiateRecord (hook)
* @param identifier
* @param createRecordArgs
* @param recordDataFor deprecated use this.cache
* @param notificationManager deprecated use this.notifications
* @returns A record instance
* @public
*/
/**
* A hook which an app or addon may implement. Called when
* the Store is destroying a Record Instance. This hook should
* be used to teardown any custom record instances instantiated
* with `instantiateRecord`.
*
* @method teardownRecord (hook)
* @public
* @param record
*/
/**
* Provides access to the SchemaDefinitionService instance
* for this Store instance.
*
* The SchemaDefinitionService can be used to query for
* information about the schema of a resource.
*
* @method getSchemaDefinitionService
* @public
*/
getSchemaDefinitionService(): SchemaService {
assert(`You must registerSchemaDefinitionService with the store to use custom model classes`, this._schema);
return this._schema;
}
/**
* DEPRECATED - Use `registerSchema` instead.
*
* Allows an app to register a custom SchemaService
* for use when information about a resource's schema needs
* to be queried.
*
* This method can only be called more than once, but only one schema
* definition service may exist. Therefore if you wish to chain services
* you must lookup the existing service and close over it with the new
* service by accessing `store.schema` prior to registration.
*
* For Example:
*
* ```ts
* import Store from '@ember-data/store';
*
* class SchemaDelegator {
* constructor(schema) {
* this._schema = schema;
* }
*
* doesTypeExist(type: string): boolean {
* if (AbstractSchemas.has(type)) {
* return true;
* }
* return this._schema.doesTypeExist(type);
* }
*
* attributesDefinitionFor(identifier: RecordIdentifier | { type: string }): AttributesSchema {
* return this._schema.attributesDefinitionFor(identifier);
* }
*
* relationshipsDefinitionFor(identifier: RecordIdentifier | { type: string }): RelationshipsSchema {
* const schema = AbstractSchemas.get(identifier.type);
* return schema || this._schema.relationshipsDefinitionFor(identifier);
* }
* }
*
* export default class extends Store {
* constructor(...args) {
* super(...args);
*
* const schema = this.schema;
* this.registerSchemaDefinitionService(new SchemaDelegator(schema));
* }
* }
* ```
*
* @method registerSchemaDefinitionService
* @param {SchemaService} schema
* @deprecated
* @public
*/
registerSchemaDefinitionService(schema: SchemaService) {
this._schema = schema;
}
/**
* Allows an app to register a custom SchemaService
* for use when information about a resource's schema needs
* to be queried.
*
* This method can only be called more than once, but only one schema
* definition service may exist. Therefore if you wish to chain services
* you must lookup the existing service and close over it with the new
* service by accessing `store.schema` prior to registration.
*
* For Example:
*
* ```ts
* import Store from '@ember-data/store';
*
* class SchemaDelegator {
* constructor(schema) {
* this._schema = schema;
* }
*
* doesTypeExist(type: string): boolean {
* if (AbstractSchemas.has(type)) {
* return true;
* }
* return this._schema.doesTypeExist(type);
* }
*
* attributesDefinitionFor(identifier: RecordIdentifier | { type: string }): AttributesSchema {
* return this._schema.attributesDefinitionFor(identifier);
* }
*
* relationshipsDefinitionFor(identifier: RecordIdentifier | { type: string }): RelationshipsSchema {
* const schema = AbstractSchemas.get(identifier.type);
* return schema || this._schema.relationshipsDefinitionFor(identifier);
* }
* }
*
* export default class extends Store {
* constructor(...args) {
* super(...args);
*
* const schema = this.schema;
* this.registerSchema(new SchemaDelegator(schema));
* }
* }
* ```
*
* @method registerSchema
* @param {SchemaService} schema
* @public
*/
registerSchema(schema: SchemaService) {
this._schema = schema;
}
/**
Returns the schema for a particular `modelName`.
When used with Model from @ember-data/model the return is the model class,
but this is not guaranteed.
If looking to query attribute or relationship information it is
recommended to use `getSchemaDefinitionService` instead. This method
should be considered legacy and exists primarily to continue to support
Adapter/Serializer APIs which expect it's return value in their method
signatures.
The class of a model might be useful if you want to get a list of all the
relationship names of the model, see
[`relationshipNames`](/ember-data/release/classes/Model?anchor=relationshipNames)
for example.
@method modelFor
@public
@param {String} type
@return {ModelSchema}
*/
// TODO @deprecate in favor of schema APIs, requires adapter/serializer overhaul or replacement
modelFor(type: string): ModelSchema {
if (DEBUG) {
assertDestroyedStoreOnly(this, 'modelFor');
}
assert(`You need to pass <type> to the store's modelFor method`, typeof type === 'string' && type.length);
assert(
`No model was found for '${type}' and no schema handles the type`,
this.getSchemaDefinitionService().doesTypeExist(type)
);
return getShimClass(this, type);
}
/**
Create a new record in the current store. The properties passed
to this method are set on the newly created record.
To create a new instance of a `Post`:
```js
store.createRecord('post', {
title: 'Ember is awesome!'
});
```
To create a new instance of a `Post` that has a relationship with a `User` record:
```js
let user = this.store.peekRecord('user', 1);
store.createRecord('post', {
title: 'Ember is awesome!',
user: user
});
```
@method createRecord
@public
@param {String} modelName
@param {Object} inputProperties a hash of properties to set on the
newly created record.
@return {Model} record
*/
createRecord(modelName: string, inputProperties: CreateRecordProperties): RecordInstance {
if (DEBUG) {
assertDestroyingStore(this, 'createRecord');
}
assert(`You need to pass a model name to the store's createRecord method`, modelName);
assert(
`Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`,
typeof modelName === 'string'
);
// This is wrapped in a `run.join` so that in test environments users do not need to manually wrap
// calls to `createRecord`. The run loop usage here is because we batch the joining and updating
// of record-arrays via ember's run loop, not our own.
//
// to remove this, we would need to move to a new `async` API.
let record!: RecordInstance;
this._join(() => {
let normalizedModelName = normalizeModelName(modelName);
let properties = { ...inputProperties };
// If the passed properties do not include a primary key,
// give the adapter an opportunity to generate one. Typically,
// client-side ID generators will use something like uuid.js
// to avoid conflicts.
if (properties.id === null || properties.id === undefined) {
let adapter = this.adapterFor(modelName, true);
if (adapter && adapter.generateIdForRecord) {
properties.id = adapter.generateIdForRecord(this, modelName, properties);
} else {
properties.id = null;
}
}
// Coerce ID to a string
properties.id = coerceId(properties.id);
const resource = { type: normalizedModelName, id: properties.id };
if (resource.id) {
const identifier = this.identifierCache.peekRecordIdentifier(resource as ResourceIdentifierObject);
assert(
`The id ${String(properties.id)} has already been used with another '${normalizedModelName}' record.`,
!identifier
);
}
const identifier = this.identifierCache.createIdentifierForNewRecord(resource);
const cache = this.cache;
const createOptions = normalizeProperties(this, identifier, properties);
const resultProps = cache.clientDidCreate(identifier, createOptions);
record = this._instanceCache.getRecord(identifier, resultProps);
});
return record;
}
/**
For symmetry, a record can be deleted via the store.
Example
```javascript
let post = store.createRecord('post', {
title: 'Ember is awesome!'
});
store.deleteRecord(post);
```
@method deleteRecord
@public
@param {Model} record
*/
deleteRecord(record: RecordInstance): void {
if (DEBUG) {
assertDestroyingStore(this, 'deleteRecord');
}
const identifier = peekRecordIdentifier(record);
const cache = this.cache;
assert(`expected the record to be connected to a cache`, identifier);
this._join(() => {
cache.setIsDeleted(identifier, true);
if (cache.isNew(identifier)) {
this._instanceCache.unloadRecord(identifier);
}
});
}
/**
For symmetry, a record can be unloaded via the store.
This will cause the record to be destroyed and freed up for garbage collection.
Example
```javascript
store.findRecord('post', 1).then(function(post) {
store.unloadRecord(post);
});
```
@method unloadRecord
@public
@param {Model} record
*/
unloadRecord(record: RecordInstance): void {
if (DEBUG) {
assertDestroyingStore(this, 'unloadRecord');
}
const identifier = peekRecordIdentifier(record);
if (identifier) {
this._instanceCache.unloadRecord(identifier);
}
}
/**
This method returns a record for a given identifier or type and id combination.
The `findRecord` method will always resolve its promise with the same
object for a given identifier or type and `id`.
The `findRecord` method will always return a **promise** that will be
resolved with the record.
**Example 1**
```app/routes/post.js
import Route from '@ember/routing/route';
export default class PostRoute extends Route {
model({ post_id }) {
return this.store.findRecord('post', post_id);
}
}
```
**Example 2**
`findRecord` can be called with a single identifier argument instead of the combination
of `type` (modelName) and `id` as separate arguments. You may recognize this combo as
the typical pairing from [JSON:API](https://jsonapi.org/format/#document-resource-object-identification)
```app/routes/post.js
import Route from '@ember/routing/route';
export default class PostRoute extends Route {
model({ post_id: id }) {
return this.store.findRecord({ type: 'post', id });
}
}
```
**Example 3**
If you have previously received an lid via an Identifier for this record, and the record
has already been assigned an id, you can find the record again using just the lid.
```app/routes/post.js
store.findRecord({ lid });
```
If the record is not yet available, the store will ask the adapter's `findRecord`
method to retrieve and supply the necessary data. If the record is already present
in the store, it depends on the reload behavior _when_ the returned promise
resolves.
### Preloading
You can optionally `preload` specific attributes and relationships that you know of
by passing them via the passed `options`.
For example, if your Ember route looks like `/posts/1/comments/2` and your API route
for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment
without also fetching the post you can pass in the post to the `findRecord` call:
```app/routes/post-comments.js
import Route from '@ember/routing/route';
export default class PostRoute extends Route {
model({ post_id, comment_id: id }) {
return this.store.findRecord({ type: 'comment', id, { preload: { post: post_id }} });
}
}
```
In your adapter you can then access this id without triggering a network request via the
snapshot:
```app/adapters/application.js
import EmberObject from '@ember/object';
export default class Adapter extends EmberObject {
findRecord(store, schema, id, snapshot) {
let type = schema.modelName;
if (type === 'comment')
let postId = snapshot.belongsTo('post', { id: true });
return fetch(`./posts/${postId}/comments/${id}`)
.then(response => response.json())
}
}
}
```
This could also be achieved by supplying the post id to the adapter via the adapterOptions
property on the options hash.
```app/routes/post-comments.js
import Route from '@ember/routing/route';
export default class PostRoute extends Route {
model({ post_id, comment_id: id }) {
return this.store.findRecord({ type: 'comment', id, { adapterOptions: { post: post_id }} });
}
}
```
```app/adapters/application.js
import EmberObject from '@ember/object';
export default class Adapter extends EmberObject {
findRecord(store, schema, id, snapshot) {
let type = schema.modelName;
if (type === 'comment')
let postId = snapshot.adapterOptions.post;
return fetch(`./posts/${postId}/comments/${id}`)
.then(response => response.json())
}
}
}
```
If you have access to the post model you can also pass the model itself to preload:
```javascript
let post = await store.findRecord('post', 1);
let comment = await store.findRecord('comment', 2, { post: myPostModel });
```
### Reloading
The reload behavior is configured either via the passed `options` hash or
the result of the adapter's `shouldReloadRecord`.
If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates
to `true`, then the returned promise resolves once the adapter returns
data, regardless if the requested record is already in the store:
```js
store.push({
data: {
id: 1,
type: 'post',
revision: 1
}
});
// adapter#findRecord resolves with
// [
// {
// id: 1,
// type: 'post',
// revision: 2
// }
// ]
store.findRecord('post', 1, { reload: true }).then(function(post) {
post.revision; // 2
});
```
If no reload is indicated via the above mentioned ways, then the promise
immediately resolves with the cached version in the store.
### Background Reloading
Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`,
then a background reload is started, which updates the records' data, once
it is available:
```js
// app/adapters/post.js
import ApplicationAdapter from "./application";
export default class PostAdapter extends ApplicationAdapter {
shouldReloadRecord(store, snapshot) {
return false;
},
shouldBackgroundReloadRecord(store, snapshot) {
return true;
}
});
// ...
store.push({
data: {
id: 1,
type: 'post',
revision: 1
}
});
let blogPost = store.findRecord('post', 1).then(function(post) {
post.revision; // 1
});
// later, once adapter#findRecord resolved with
// [
// {
// id: 1,
// type: 'post',
// revision: 2
// }
// ]
blogPost.revision; // 2
```
If you would like to force or prevent background reloading, you can set a
boolean value for `backgroundReload` in the options object for
`findRecord`.
```app/routes/post/edit.js
import Route from '@ember/routing/route';
export default class PostEditRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { backgroundReload: false });
}
}
```
If you pass an object on the `adapterOptions` property of the options
argument it will be passed to your adapter via the snapshot
```app/routes/post/edit.js
import Route from '@ember/routing/route';
export default class PostEditRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, {