-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathstore-service.ts
2896 lines (2439 loc) · 92.1 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
*/
import { getOwner, setOwner } from '@ember/application';
import { assert, deprecate } from '@ember/debug';
import { _backburner as emberBackburner } from '@ember/runloop';
import Service from '@ember/service';
import { registerWaiter, unregisterWaiter } from '@ember/test';
import { DEBUG } from '@glimmer/env';
import { importSync } from '@embroider/macros';
import { reject, resolve } from 'rsvp';
import type DSModelClass from '@ember-data/model';
import { HAS_MODEL_PACKAGE, HAS_RECORD_DATA_PACKAGE } from '@ember-data/private-build-infra';
import { LOG_PAYLOADS } from '@ember-data/private-build-infra/debugging';
import {
DEPRECATE_HAS_RECORD,
DEPRECATE_JSON_API_FALLBACK,
DEPRECATE_PROMISE_PROXIES,
DEPRECATE_STORE_FIND,
DEPRECATE_V1CACHE_STORE_APIS,
} from '@ember-data/private-build-infra/deprecations';
import type { RecordData as RecordDataClass } from '@ember-data/record-data/-private';
import type { DSModel } 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 { RecordData, RecordDataV1 } from '@ember-data/types/q/record-data';
import { JsonApiValidationError } from '@ember-data/types/q/record-data-json-api';
import type { RecordDataStoreWrapper } from '@ember-data/types/q/record-data-store-wrapper';
import type { RecordInstance } from '@ember-data/types/q/record-instance';
import type { SchemaDefinitionService } from '@ember-data/types/q/schema-definition-service';
import type { FindOptions } from '@ember-data/types/q/store';
import type { Dict } from '@ember-data/types/q/utils';
import { IdentifierCache } from './caches/identifier-cache';
import {
InstanceCache,
peekRecordIdentifier,
recordDataIsFullyDeleted,
recordIdentifierFor,
setRecordIdentifier,
storeFor,
StoreMap,
} from './caches/instance-cache';
import recordDataFor, { setRecordDataFor } from './caches/record-data-for';
import RecordReference from './legacy-model-support/record-reference';
import { DSModelSchemaDefinitionService, getModelFactory } from './legacy-model-support/schema-definition-service';
import type ShimModelClass from './legacy-model-support/shim-model-class';
import { getShimClass } from './legacy-model-support/shim-model-class';
import RecordArrayManager from './managers/record-array-manager';
import type { NonSingletonRecordDataManager } from './managers/record-data-manager';
import NotificationManager from './managers/record-notification-manager';
import FetchManager, { SaveOp } from './network/fetch-manager';
import { _findAll, _query, _queryRecord } from './network/finders';
import type RequestCache from './network/request-cache';
import type Snapshot from './network/snapshot';
import SnapshotRecordArray from './network/snapshot-record-array';
import { PromiseArray, promiseArray, PromiseObject, promiseObject } from './proxies/promise-proxies';
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';
import promiseRecord from './utils/promise-record';
export { storeFor };
// hello world
type RecordDataConstruct = typeof RecordDataClass;
let _RecordData: RecordDataConstruct | undefined;
type AsyncTrackingToken = Readonly<{ label: string; trace: Error | string }>;
function freeze<T>(obj: T): T {
if (typeof Object.freeze === 'function') {
return Object.freeze(obj);
}
return obj;
}
export interface CreateRecordProperties {
id?: string | null;
[key: string]: unknown;
}
/**
The store contains all of the data for records loaded from the server.
It is also responsible for creating instances of `Model` that wrap
the individual data for a record, so that they can be bound to in your
Handlebars templates.
Define your application's store like this:
```app/services/store.js
import Store from '@ember-data/store';
export default class MyStore extends Store {}
```
Most Ember.js applications will only have a single `Store` that is
automatically created by their `Ember.Application`.
You can retrieve models from the store in several ways. To retrieve a record
for a specific id, use `Store`'s `findRecord()` method:
```javascript
store.findRecord('person', 123).then(function (person) {
});
```
By default, the store will talk to your backend using a standard
REST mechanism. You can customize how the store talks to your
backend by specifying a custom adapter:
```app/adapters/application.js
import Adapter from '@ember-data/adapter';
export default class ApplicationAdapter extends Adapter {
}
```
You can learn more about writing a custom adapter by reading the `Adapter`
documentation.
### Store createRecord() vs. push() vs. pushPayload()
The store provides multiple ways to create new record objects. They have
some subtle differences in their use which are detailed below:
[createRecord](../methods/createRecord?anchor=createRecord) is used for creating new
records on the client side. This will return a new record in the
`created.uncommitted` state. In order to persist this record to the
backend, you will need to call `record.save()`.
[push](../methods/push?anchor=push) is used to notify Ember Data's store of new or
updated records that exist in the backend. This will return a record
in the `loaded.saved` state. The primary use-case for `store#push` is
to notify Ember Data about record updates (full or partial) that happen
outside of the normal adapter methods (for example
[SSE](http://dev.w3.org/html5/eventsource/) or [Web
Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)).
[pushPayload](../methods/pushPayload?anchor=pushPayload) is a convenience wrapper for
`store#push` that will deserialize payloads if the
Serializer implements a `pushPayload` method.
Note: When creating a new record using any of the above methods
Ember Data will update `RecordArray`s such as those returned by
`store#peekAll()` or `store#findAll()`. This means any
data bindings or computed properties that depend on the RecordArray
will automatically be synced to include the new or updated record
values.
@main @ember-data/store
@class Store
@public
@extends Ember.Service
*/
class Store extends Service {
__private_singleton_recordData!: RecordData;
declare recordArrayManager: RecordArrayManager;
declare _notificationManager: NotificationManager;
declare identifierCache: IdentifierCache;
declare _adapterCache: Dict<MinimumAdapterInterface & { store: Store }>;
declare _serializerCache: Dict<MinimumSerializerInterface & { store: Store }>;
declare _modelFactoryCache: Dict<unknown>;
declare _fetchManager: FetchManager;
declare _schemaDefinitionService: SchemaDefinitionService;
declare _instanceCache: InstanceCache;
// DEBUG-only properties
declare _trackedAsyncRequests: AsyncTrackingToken[];
declare generateStackTracesForTrackedRequests: boolean;
declare _trackAsyncRequestStart: (str: string) => void;
declare _trackAsyncRequestEnd: (token: AsyncTrackingToken) => void;
declare __asyncWaiter: () => boolean;
declare DISABLE_WAITER?: boolean;
/**
@method init
@private
*/
constructor() {
super(...arguments);
/**
* 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
*/
this.identifierCache = new IdentifierCache();
// private but maybe useful to be here, somewhat intimate
this.recordArrayManager = new RecordArrayManager({ store: this });
// private, TODO consider taking public as the instance is public to instantiateRecord anyway
this._notificationManager = new NotificationManager(this);
// private
this._fetchManager = new FetchManager(this);
this._instanceCache = new InstanceCache(this);
this._adapterCache = Object.create(null);
this._serializerCache = Object.create(null);
this._modelFactoryCache = Object.create(null);
if (DEBUG) {
if (this.generateStackTracesForTrackedRequests === undefined) {
this.generateStackTracesForTrackedRequests = false;
}
this._trackedAsyncRequests = [];
this._trackAsyncRequestStart = (label) => {
let trace: string | Error =
'set `store.generateStackTracesForTrackedRequests = true;` to get a detailed trace for where this request originated';
if (this.generateStackTracesForTrackedRequests) {
try {
throw new Error(`EmberData TrackedRequest: ${label}`);
} catch (e) {
trace = e as Error;
}
}
let token = freeze({
label,
trace,
});
this._trackedAsyncRequests.push(token);
return token;
};
this._trackAsyncRequestEnd = (token) => {
let index = this._trackedAsyncRequests.indexOf(token);
if (index === -1) {
throw new Error(
`Attempted to end tracking for the following request but it was not being tracked:\n${token}`
);
}
this._trackedAsyncRequests.splice(index, 1);
};
this.__asyncWaiter = () => {
let tracked = this._trackedAsyncRequests;
return this.DISABLE_WAITER || tracked.length === 0;
};
registerWaiter(this.__asyncWaiter);
}
}
declare _cbs: { coalesce?: () => void; sync?: () => void; notify?: () => void } | null;
_run(cb: () => void) {
assert(`EmberData should never encounter a nested run`, !this._cbs);
const _cbs: { coalesce?: () => void; sync?: () => void; notify?: () => void } = (this._cbs = {});
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(): RequestCache {
return this._fetchManager.requestCache;
}
/**
* 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
* @param notificationManager
* @returns A record instance
* @public
*/
instantiateRecord(
identifier: StableRecordIdentifier,
createRecordArgs: { [key: string]: unknown },
recordDataFor: (identifier: StableRecordIdentifier) => RecordData,
notificationManager: NotificationManager
): DSModel | RecordInstance {
if (HAS_MODEL_PACKAGE) {
let modelName = identifier.type;
let recordData = this._instanceCache.getRecordData(identifier);
// TODO deprecate allowing unknown args setting
let createOptions: any = {
_createProps: createRecordArgs,
// TODO @deprecate consider deprecating accessing record properties during init which the below is necessary for
_secretInit: {
identifier,
recordData,
store: this,
cb: secretInit,
},
};
// ensure that `getOwner(this)` works inside a model instance
setOwner(createOptions, getOwner(this));
return getModelFactory(this, this._modelFactoryCache, modelName).class.create(createOptions);
}
assert(`You must implement the store's instantiateRecord hook for your custom model class.`);
}
/**
* 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
*/
teardownRecord(record: DSModel | RecordInstance): void {
if (HAS_MODEL_PACKAGE) {
assert(
`expected to receive an instance of DSModel. If using a custom model make sure you implement teardownRecord`,
'destroy' in record
);
(record as DSModel).destroy();
} else {
assert(`You must implement the store's teardownRecord hook for your custom models`);
}
}
/**
* 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(): SchemaDefinitionService {
if (HAS_MODEL_PACKAGE && !this._schemaDefinitionService) {
// it is potentially a mistake for the RFC to have not enabled chaining these services, though highlander rule is nice.
// what ember-m3 did via private API to allow both worlds to interop would be much much harder using this.
this._schemaDefinitionService = new DSModelSchemaDefinitionService(this);
}
assert(
`You must registerSchemaDefinitionService with the store to use custom model classes`,
this._schemaDefinitionService
);
return this._schemaDefinitionService;
}
/**
* Allows an app to register a custom SchemaDefinitionService
* 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 calling `getSchemaDefinitionService` 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.getSchemaDefinitionService();
* this.registerSchemaDefinitionService(new SchemaDelegator(schema));
* }
* }
* ```
*
* @method registerSchemaDefinitionService
* @param {SchemaDefinitionService} schema
* @public
*/
registerSchemaDefinitionService(schema: SchemaDefinitionService) {
this._schemaDefinitionService = 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} modelName
@return {subclass of Model | ShimModelClass}
*/
// TODO @deprecate in favor of schema APIs, requires adapter/serializer overhaul or replacement
modelFor(modelName: string): ShimModelClass | DSModelClass {
if (DEBUG) {
assertDestroyedStoreOnly(this, 'modelFor');
}
assert(`You need to pass a model name to the store's modelFor method`, modelName);
assert(
`Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`,
typeof modelName === 'string'
);
if (HAS_MODEL_PACKAGE) {
let normalizedModelName = normalizeModelName(modelName);
let maybeFactory = getModelFactory(this, this._modelFactoryCache, normalizedModelName);
// for factorFor factory/class split
let klass = maybeFactory && maybeFactory.class ? maybeFactory.class : maybeFactory;
if (!klass || !klass.isModel) {
assert(
`No model was found for '${modelName}' and no schema handles the type`,
this.getSchemaDefinitionService().doesTypeExist(modelName)
);
return getShimClass(this, modelName);
} else {
// TODO @deprecate ever returning the klass, always return the shim
return klass;
}
}
assert(
`No model was found for '${modelName}' and no schema handles the type`,
this.getSchemaDefinitionService().doesTypeExist(modelName)
);
return getShimClass(this, modelName);
}
/**
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;
emberBackburner.join(() => {
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);
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 ${properties.id} has already been used with another '${normalizedModelName}' record.`,
!identifier
);
}
const identifier = this.identifierCache.createIdentifierForNewRecord(resource);
const recordData = this._instanceCache.getRecordData(identifier);
const createOptions = normalizeProperties(
this,
identifier,
properties,
(recordData as NonSingletonRecordDataManager).managedVersion === '1'
);
const resultProps = recordData.clientDidCreate(identifier, createOptions);
this.recordArrayManager.identifierAdded(identifier);
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 recordData = identifier && this._instanceCache.peek({ identifier, bucket: 'recordData' });
assert(`expected a recordData instance to exist for the record`, recordData);
this._join(() => {
recordData.setIsDeleted(identifier, true);
if (recordData.isNew(identifier)) {
emberBackburner.join(() => {
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);
}
}
/**
@method find
@param {String} modelName
@param {String|Integer} id
@param {Object} options
@return {Promise} promise
@deprecated
@private
*/
find(modelName: string, id: string | number, options?): PromiseObject<RecordInstance> {
if (DEBUG) {
assertDestroyingStore(this, 'find');
}
// The default `model` hook in Route calls `find(modelName, id)`,
// that's why we have to keep this method around even though `findRecord` is
// the public way to get a record by modelName and id.
assert(
`Using store.find(type) has been removed. Use store.findAll(modelName) to retrieve all records for a given type.`,
arguments.length !== 1
);
assert(
`Calling store.find(modelName, id, { preload: preload }) is no longer supported. Use store.findRecord(modelName, id, { preload: preload }) instead.`,
!options
);
assert(`You need to pass the model name and id to the store's find method`, arguments.length === 2);
assert(
`You cannot pass '${id}' as id to the store's find method`,
typeof id === 'string' || typeof id === 'number'
);
assert(
`Calling store.find() with a query object is no longer supported. Use store.query() instead.`,
typeof id !== 'object'
);
assert(
`Passing classes to store methods has been removed. Please pass a dasherized string instead of ${modelName}`,
typeof modelName === 'string'
);
if (DEPRECATE_STORE_FIND) {
deprecate(
`Using store.find is deprecated, use store.findRecord instead. Likely this means you are relying on the implicit store fetching behavior of routes unknowingly.`,
false,
{
id: 'ember-data:deprecate-store-find',
since: { available: '4.5', enabled: '4.5' },
for: 'ember-data',
until: '5.0',
}
);
return this.findRecord(modelName, id);
}
assert(`store.find has been removed. Use store.findRecord instead.`);
}
/**
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, {
adapterOptions: { subscribe: false }
});
}
}
```
```app/adapters/post.js
import MyCustomAdapter from './custom-adapter';
export default class PostAdapter extends MyCustomAdapter {
findRecord(store, type, id, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
}
```
See [peekRecord](../methods/peekRecord?anchor=peekRecord) to get the cached version of a record.
### Retrieving Related Model Records
If you use an adapter such as Ember's default
[`JSONAPIAdapter`](/ember-data/release/classes/JSONAPIAdapter)
that supports the [JSON API specification](http://jsonapi.org/) and if your server
endpoint supports the use of an
['include' query parameter](http://jsonapi.org/format/#fetching-includes),
you can use `findRecord()` or `findAll()` to automatically retrieve additional records related to
the one you request by supplying an `include` parameter in the `options` object.
For example, given a `post` model that has a `hasMany` relationship with a `comment`
model, when we retrieve a specific post we can have the server also return that post's
comments in the same request:
```app/routes/post.js
import Route from '@ember/routing/route';