@ember-data-types/store 5.4.0-alpha.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE.md +11 -0
  2. package/README.md +193 -0
  3. package/ember-data-logo-dark.svg +12 -0
  4. package/ember-data-logo-light.svg +12 -0
  5. package/package.json +20 -0
  6. package/unstable-preview-types/-private/cache-handler.d.ts +100 -0
  7. package/unstable-preview-types/-private/cache-handler.d.ts.map +1 -0
  8. package/unstable-preview-types/-private/caches/cache-utils.d.ts +11 -0
  9. package/unstable-preview-types/-private/caches/cache-utils.d.ts.map +1 -0
  10. package/unstable-preview-types/-private/caches/identifier-cache.d.ts +182 -0
  11. package/unstable-preview-types/-private/caches/identifier-cache.d.ts.map +1 -0
  12. package/unstable-preview-types/-private/caches/instance-cache.d.ts +63 -0
  13. package/unstable-preview-types/-private/caches/instance-cache.d.ts.map +1 -0
  14. package/unstable-preview-types/-private/caches/resource-utils.d.ts +12 -0
  15. package/unstable-preview-types/-private/caches/resource-utils.d.ts.map +1 -0
  16. package/unstable-preview-types/-private/document.d.ts +146 -0
  17. package/unstable-preview-types/-private/document.d.ts.map +1 -0
  18. package/unstable-preview-types/-private/legacy-model-support/record-reference.d.ts +179 -0
  19. package/unstable-preview-types/-private/legacy-model-support/record-reference.d.ts.map +1 -0
  20. package/unstable-preview-types/-private/legacy-model-support/shim-model-class.d.ts +19 -0
  21. package/unstable-preview-types/-private/legacy-model-support/shim-model-class.d.ts.map +1 -0
  22. package/unstable-preview-types/-private/managers/cache-capabilities-manager.d.ts +29 -0
  23. package/unstable-preview-types/-private/managers/cache-capabilities-manager.d.ts.map +1 -0
  24. package/unstable-preview-types/-private/managers/cache-manager.d.ts +442 -0
  25. package/unstable-preview-types/-private/managers/cache-manager.d.ts.map +1 -0
  26. package/unstable-preview-types/-private/managers/notification-manager.d.ts +98 -0
  27. package/unstable-preview-types/-private/managers/notification-manager.d.ts.map +1 -0
  28. package/unstable-preview-types/-private/managers/record-array-manager.d.ts +97 -0
  29. package/unstable-preview-types/-private/managers/record-array-manager.d.ts.map +1 -0
  30. package/unstable-preview-types/-private/network/request-cache.d.ts +109 -0
  31. package/unstable-preview-types/-private/network/request-cache.d.ts.map +1 -0
  32. package/unstable-preview-types/-private/record-arrays/identifier-array.d.ts +133 -0
  33. package/unstable-preview-types/-private/record-arrays/identifier-array.d.ts.map +1 -0
  34. package/unstable-preview-types/-private/record-arrays/native-proxy-type-fix.d.ts +118 -0
  35. package/unstable-preview-types/-private/record-arrays/native-proxy-type-fix.d.ts.map +1 -0
  36. package/unstable-preview-types/-private/store-service.d.ts +1554 -0
  37. package/unstable-preview-types/-private/store-service.d.ts.map +1 -0
  38. package/unstable-preview-types/-private/utils/coerce-id.d.ts +10 -0
  39. package/unstable-preview-types/-private/utils/coerce-id.d.ts.map +1 -0
  40. package/unstable-preview-types/-private/utils/construct-resource.d.ts +10 -0
  41. package/unstable-preview-types/-private/utils/construct-resource.d.ts.map +1 -0
  42. package/unstable-preview-types/-private/utils/identifier-debug-consts.d.ts +7 -0
  43. package/unstable-preview-types/-private/utils/identifier-debug-consts.d.ts.map +1 -0
  44. package/unstable-preview-types/-private/utils/is-non-empty-string.d.ts +4 -0
  45. package/unstable-preview-types/-private/utils/is-non-empty-string.d.ts.map +1 -0
  46. package/unstable-preview-types/-private/utils/normalize-model-name.d.ts +4 -0
  47. package/unstable-preview-types/-private/utils/normalize-model-name.d.ts.map +1 -0
  48. package/unstable-preview-types/-private/utils/uuid-polyfill.d.ts +4 -0
  49. package/unstable-preview-types/-private/utils/uuid-polyfill.d.ts.map +1 -0
  50. package/unstable-preview-types/-private.d.ts +20 -0
  51. package/unstable-preview-types/-private.d.ts.map +1 -0
  52. package/unstable-preview-types/-types/overview.d.ts +21 -0
  53. package/unstable-preview-types/-types/overview.d.ts.map +1 -0
  54. package/unstable-preview-types/-types/q/cache-store-wrapper.d.ts +107 -0
  55. package/unstable-preview-types/-types/q/cache-store-wrapper.d.ts.map +1 -0
  56. package/unstable-preview-types/-types/q/cache.d.ts +47 -0
  57. package/unstable-preview-types/-types/q/cache.d.ts.map +1 -0
  58. package/unstable-preview-types/-types/q/ds-model.d.ts +15 -0
  59. package/unstable-preview-types/-types/q/ds-model.d.ts.map +1 -0
  60. package/unstable-preview-types/-types/q/identifier.d.ts +171 -0
  61. package/unstable-preview-types/-types/q/identifier.d.ts.map +1 -0
  62. package/unstable-preview-types/-types/q/promise-proxies.d.ts +4 -0
  63. package/unstable-preview-types/-types/q/promise-proxies.d.ts.map +1 -0
  64. package/unstable-preview-types/-types/q/record-data-json-api.d.ts +36 -0
  65. package/unstable-preview-types/-types/q/record-data-json-api.d.ts.map +1 -0
  66. package/unstable-preview-types/-types/q/record-instance.d.ts +29 -0
  67. package/unstable-preview-types/-types/q/record-instance.d.ts.map +1 -0
  68. package/unstable-preview-types/-types/q/schema-service.d.ts +214 -0
  69. package/unstable-preview-types/-types/q/schema-service.d.ts.map +1 -0
  70. package/unstable-preview-types/-types/q/store.d.ts +17 -0
  71. package/unstable-preview-types/-types/q/store.d.ts.map +1 -0
  72. package/unstable-preview-types/index.d.ts +220 -0
  73. package/unstable-preview-types/index.d.ts.map +1 -0
@@ -0,0 +1,1554 @@
1
+ declare module '@ember-data/store/-private/store-service' {
2
+ /// <reference types="ember-source/types" />
3
+ import EmberObject from '@ember/object';
4
+ import type RequestManager from '@ember-data/request';
5
+ import type { Future } from '@ember-data/request/-private/types';
6
+ import type { Graph } from '@warp-drive/core-types/graph';
7
+ import type { StableDocumentIdentifier, StableExistingRecordIdentifier, StableRecordIdentifier } from '@warp-drive/core-types/identifier';
8
+ import type { TypedRecordInstance, TypeFromInstance } from '@warp-drive/core-types/record';
9
+ import type { CollectionResourceDocument, EmptyResourceDocument, JsonApiDocument, ResourceIdentifierObject, SingleResourceDocument } from '@warp-drive/core-types/spec/raw';
10
+ import type { ResourceType } from '@warp-drive/core-types/symbols';
11
+ import type { Cache, CacheV1 } from '@ember-data/store/-types/q/cache';
12
+ import type { CacheCapabilitiesManager } from '@ember-data/store/-types/q/cache-store-wrapper';
13
+ import type { ModelSchema } from '@ember-data/store/-types/q/ds-model';
14
+ import type { OpaqueRecordInstance } from '@ember-data/store/-types/q/record-instance';
15
+ import type { SchemaService } from '@ember-data/store/-types/q/schema-service';
16
+ import type { FindAllOptions, FindRecordOptions, QueryOptions } from '@ember-data/store/-types/q/store';
17
+ import type { LifetimesService, StoreRequestInput } from '@ember-data/store/-private/cache-handler';
18
+ import { IdentifierCache } from '@ember-data/store/-private/caches/identifier-cache';
19
+ import { InstanceCache, storeFor } from '@ember-data/store/-private/caches/instance-cache';
20
+ import type { Document } from '@ember-data/store/-private/document';
21
+ import type RecordReference from '@ember-data/store/-private/legacy-model-support/record-reference';
22
+ import NotificationManager from '@ember-data/store/-private/managers/notification-manager';
23
+ import RecordArrayManager from '@ember-data/store/-private/managers/record-array-manager';
24
+ import RequestStateService from '@ember-data/store/-private/network/request-cache';
25
+ import type { Collection } from '@ember-data/store/-private/record-arrays/identifier-array';
26
+ import type IdentifierArray from '@ember-data/store/-private/record-arrays/identifier-array';
27
+ export { storeFor };
28
+ type FilteredKeys<T> = Omit<T, typeof ResourceType | keyof EmberObject | 'constructor'>;
29
+ type MaybeHasId = {
30
+ id?: string | null;
31
+ };
32
+ /**
33
+ * Currently only records that extend object can be created via
34
+ * store.createRecord. This is a limitation of the current API,
35
+ * but can be worked around by creating a new identifier, running
36
+ * the cache.clientDidCreate method, and then peeking the record
37
+ * for the identifier.
38
+ *
39
+ * To assign primary key to a record during creation, only `id` will
40
+ * work correctly for `store.createRecord`, other primary key may be
41
+ * handled by updating the record after creation or using the flow
42
+ * described above.
43
+ *
44
+ * TODO: These are limitations we want to (and can) address. If you
45
+ * have need of lifting these limitations, please open an issue.
46
+ *
47
+ * @typedoc
48
+ */
49
+ export type CreateRecordProperties<T = MaybeHasId & Record<string, unknown>> = T extends TypedRecordInstance ? FilteredKeys<Partial<T>> : T extends MaybeHasId ? MaybeHasId & FilteredKeys<Partial<T>> : MaybeHasId & Record<string, unknown>;
50
+ /**
51
+ * A Store coordinates interaction between your application, a [Cache](https://api.emberjs.com/ember-data/release/classes/%3CInterface%3E%20Cache),
52
+ * and sources of data (such as your API or a local persistence layer)
53
+ * accessed via a [RequestManager](https://github.com/emberjs/data/tree/main/packages/request).
54
+ *
55
+ * ```app/services/store.js
56
+ * import Store from '@ember-data/store';
57
+ *
58
+ * export default class extends Store {}
59
+ * ```
60
+ *
61
+ * Most Ember applications will only have a single `Store` configured as a Service
62
+ * in this manner. However, setting up multiple stores is possible, including using
63
+ * each as a unique service.
64
+ *
65
+
66
+ @class Store
67
+ @public
68
+ */
69
+ interface Store {
70
+ createRecordDataFor?(identifier: StableRecordIdentifier, wrapper: CacheCapabilitiesManager): Cache | CacheV1;
71
+ createCache(storeWrapper: CacheCapabilitiesManager): Cache;
72
+ instantiateRecord(identifier: StableRecordIdentifier, createRecordArgs: {
73
+ [key: string]: unknown;
74
+ }): OpaqueRecordInstance;
75
+ teardownRecord(record: OpaqueRecordInstance): void;
76
+ }
77
+ class Store extends EmberObject {
78
+ recordArrayManager: RecordArrayManager;
79
+ /**
80
+ * Provides access to the NotificationManager associated
81
+ * with this Store instance.
82
+ *
83
+ * The NotificationManager can be used to subscribe to
84
+ * changes to the cache.
85
+ *
86
+ * @property {NotificationManager} notifications
87
+ * @public
88
+ */
89
+ notifications: NotificationManager;
90
+ /**
91
+ * Provides access to the SchemaService instance
92
+ * for this Store instance.
93
+ *
94
+ * The SchemaService can be used to query for
95
+ * information about the schema of a resource.
96
+ *
97
+ * @property {SchemaService} schema
98
+ * @public
99
+ */
100
+ get schema(): SchemaService;
101
+ _schema: SchemaService;
102
+ /**
103
+ * Provides access to the IdentifierCache instance
104
+ * for this store.
105
+ *
106
+ * The IdentifierCache can be used to generate or
107
+ * retrieve a stable unique identifier for any resource.
108
+ *
109
+ * @property {IdentifierCache} identifierCache
110
+ * @public
111
+ */
112
+ identifierCache: IdentifierCache;
113
+ /**
114
+ * Provides access to the requestManager instance associated
115
+ * with this Store instance.
116
+ *
117
+ * When using `ember-data` this property is automatically
118
+ * set to an instance of `RequestManager`. When not using `ember-data`
119
+ * you must configure this property yourself, either by declaring
120
+ * it as a service or by initializing it.
121
+ *
122
+ * ```ts
123
+ * import Store, { CacheHandler } from '@ember-data/store';
124
+ * import RequestManager from '@ember-data/request';
125
+ * import Fetch from '@ember/data/request/fetch';
126
+ *
127
+ * class extends Store {
128
+ * constructor() {
129
+ * super(...arguments);
130
+ * this.requestManager = new RequestManager();
131
+ * this.requestManager.use([Fetch]);
132
+ * this.requestManager.useCache(CacheHandler);
133
+ * }
134
+ * }
135
+ * ```
136
+ *
137
+ * @public
138
+ * @property {RequestManager} requestManager
139
+ */
140
+ requestManager: RequestManager;
141
+ /**
142
+ * A Property which an App may set to provide a Lifetimes Service
143
+ * to control when a cached request becomes stale.
144
+ *
145
+ * Note, when defined, these methods will only be invoked if a
146
+ * cache key exists for the request, either because the request
147
+ * contains `cacheOptions.key` or because the [IdentifierCache](/ember-data/release/classes/IdentifierCache)
148
+ * was able to generate a key for the request using the configured
149
+ * [generation method](/ember-data/release/functions/@ember-data%2Fstore/setIdentifierGenerationMethod).
150
+ *
151
+ * `isSoftExpired` will only be invoked if `isHardExpired` returns `false`.
152
+ *
153
+ * ```ts
154
+ * store.lifetimes = {
155
+ * // make the request and ignore the current cache state
156
+ * isHardExpired(identifier: StableDocumentIdentifier): boolean {
157
+ * return false;
158
+ * }
159
+ *
160
+ * // make the request in the background if true, return cache state
161
+ * isSoftExpired(identifier: StableDocumentIdentifier): boolean {
162
+ * return false;
163
+ * }
164
+ * }
165
+ * ```
166
+ *
167
+ * @public
168
+ * @property {LivetimesService|undefined} lifetimes
169
+ */
170
+ lifetimes?: LifetimesService;
171
+ _graph?: Graph;
172
+ _requestCache: RequestStateService;
173
+ _instanceCache: InstanceCache;
174
+ _documentCache: Map<StableDocumentIdentifier, Document<OpaqueRecordInstance | OpaqueRecordInstance[] | null | undefined>>;
175
+ _cbs: {
176
+ coalesce?: () => void;
177
+ sync?: () => void;
178
+ notify?: () => void;
179
+ } | null;
180
+ _forceShim: boolean;
181
+ _enableAsyncFlush: boolean | null;
182
+ DISABLE_WAITER?: boolean;
183
+ _isDestroying: boolean;
184
+ _isDestroyed: boolean;
185
+ get isDestroying(): boolean;
186
+ set isDestroying(value: boolean);
187
+ get isDestroyed(): boolean;
188
+ set isDestroyed(value: boolean);
189
+ /**
190
+ @method init
191
+ @private
192
+ */
193
+ constructor(createArgs?: unknown);
194
+ _run(cb: () => void): void;
195
+ _join(cb: () => void): void;
196
+ _schedule(name: 'coalesce' | 'sync' | 'notify', cb: () => void): void;
197
+ /**
198
+ * Retrieve the RequestStateService instance
199
+ * associated with this Store.
200
+ *
201
+ * This can be used to query the status of requests
202
+ * that have been initiated for a given identifier.
203
+ *
204
+ * @method getRequestStateService
205
+ * @return {RequestStateService}
206
+ * @public
207
+ */
208
+ getRequestStateService(): RequestStateService;
209
+ _getAllPending(): (Promise<unknown[]> & {
210
+ length: number;
211
+ }) | void;
212
+ /**
213
+ * Issue a request via the configured RequestManager,
214
+ * inserting the response into the cache and handing
215
+ * back a Future which resolves to a ResponseDocument
216
+ *
217
+ * ## Cache Keys
218
+ *
219
+ * Only GET requests with a url or requests with an explicit
220
+ * cache key (`cacheOptions.key`) will have the request result
221
+ * and document cached.
222
+ *
223
+ * The cache key used is `requestConfig.cacheOptions.key`
224
+ * if present, falling back to `requestconfig.url`.
225
+ *
226
+ * Params are not serialized as part of the cache-key, so
227
+ * either ensure they are already in the url or utilize
228
+ * `requestConfig.cacheOptions.key`. For queries issued
229
+ * via the `POST` method `requestConfig.cacheOptions.key`
230
+ * MUST be supplied for the document to be cached.
231
+ *
232
+ * ## Requesting Without a Cache Key
233
+ *
234
+ * Resource data within the request is always updated in the cache,
235
+ * regardless of whether a cache key is present for the request.
236
+ *
237
+ * ## Fulfilling From Cache
238
+ *
239
+ * When a cache-key is determined, the request may fulfill
240
+ * from cache provided the cache is not stale.
241
+ *
242
+ * Cache staleness is determined by the configured LifetimesService
243
+ * with priority given to the `cacheOptions.reload` and
244
+ * `cacheOptions.backgroundReload` on the request if present.
245
+ *
246
+ * If the cache data has soft expired or the request asks for a background
247
+ * reload, the request will fulfill from cache if possible and
248
+ * make a non-blocking request in the background to update the cache.
249
+ *
250
+ * If the cache data has hard expired or the request asks for a reload,
251
+ * the request will not fulfill from cache and will make a blocking
252
+ * request to update the cache.
253
+ *
254
+ * ## The Response
255
+ *
256
+ * The primary difference between `requestManager.request` and `store.request`
257
+ * is that `store.request` will attempt to hydrate the response content into
258
+ * a response Document containing RecordInstances.
259
+ *
260
+ * @method request
261
+ * @param {StoreRequestInput} requestConfig
262
+ * @return {Future}
263
+ * @public
264
+ */
265
+ request<T>(requestConfig: StoreRequestInput): Future<T>;
266
+ /**
267
+ * A hook which an app or addon may implement. Called when
268
+ * the Store is attempting to create a Record Instance for
269
+ * a resource.
270
+ *
271
+ * This hook can be used to select or instantiate any desired
272
+ * mechanism of presentating cache data to the ui for access
273
+ * mutation, and interaction.
274
+ *
275
+ * @method instantiateRecord (hook)
276
+ * @param identifier
277
+ * @param createRecordArgs
278
+ * @param recordDataFor deprecated use this.cache
279
+ * @param notificationManager deprecated use this.notifications
280
+ * @return A record instance
281
+ * @public
282
+ */
283
+ /**
284
+ * A hook which an app or addon may implement. Called when
285
+ * the Store is destroying a Record Instance. This hook should
286
+ * be used to teardown any custom record instances instantiated
287
+ * with `instantiateRecord`.
288
+ *
289
+ * @method teardownRecord (hook)
290
+ * @public
291
+ * @param record
292
+ */
293
+ /**
294
+ * Provides access to the SchemaDefinitionService instance
295
+ * for this Store instance.
296
+ *
297
+ * The SchemaDefinitionService can be used to query for
298
+ * information about the schema of a resource.
299
+ *
300
+ * @method getSchemaDefinitionService
301
+ * @public
302
+ */
303
+ getSchemaDefinitionService(): SchemaService;
304
+ /**
305
+ * DEPRECATED - Use `registerSchema` instead.
306
+ *
307
+ * Allows an app to register a custom SchemaService
308
+ * for use when information about a resource's schema needs
309
+ * to be queried.
310
+ *
311
+ * This method can only be called more than once, but only one schema
312
+ * definition service may exist. Therefore if you wish to chain services
313
+ * you must lookup the existing service and close over it with the new
314
+ * service by accessing `store.schema` prior to registration.
315
+ *
316
+ * For Example:
317
+ *
318
+ * ```ts
319
+ * import Store from '@ember-data/store';
320
+ *
321
+ * class SchemaDelegator {
322
+ * constructor(schema) {
323
+ * this._schema = schema;
324
+ * }
325
+ *
326
+ * doesTypeExist(type: string): boolean {
327
+ * if (AbstractSchemas.has(type)) {
328
+ * return true;
329
+ * }
330
+ * return this._schema.doesTypeExist(type);
331
+ * }
332
+ *
333
+ * attributesDefinitionFor(identifier: RecordIdentifier | { type: string }): AttributesSchema {
334
+ * return this._schema.attributesDefinitionFor(identifier);
335
+ * }
336
+ *
337
+ * relationshipsDefinitionFor(identifier: RecordIdentifier | { type: string }): RelationshipsSchema {
338
+ * const schema = AbstractSchemas.get(identifier.type);
339
+ * return schema || this._schema.relationshipsDefinitionFor(identifier);
340
+ * }
341
+ * }
342
+ *
343
+ * export default class extends Store {
344
+ * constructor(...args) {
345
+ * super(...args);
346
+ *
347
+ * const schema = this.schema;
348
+ * this.registerSchemaDefinitionService(new SchemaDelegator(schema));
349
+ * }
350
+ * }
351
+ * ```
352
+ *
353
+ * @method registerSchemaDefinitionService
354
+ * @param {SchemaService} schema
355
+ * @deprecated
356
+ * @public
357
+ */
358
+ registerSchemaDefinitionService(schema: SchemaService): void;
359
+ /**
360
+ * Allows an app to register a custom SchemaService
361
+ * for use when information about a resource's schema needs
362
+ * to be queried.
363
+ *
364
+ * This method can only be called more than once, but only one schema
365
+ * definition service may exist. Therefore if you wish to chain services
366
+ * you must lookup the existing service and close over it with the new
367
+ * service by accessing `store.schema` prior to registration.
368
+ *
369
+ * For Example:
370
+ *
371
+ * ```ts
372
+ * import Store from '@ember-data/store';
373
+ *
374
+ * class SchemaDelegator {
375
+ * constructor(schema) {
376
+ * this._schema = schema;
377
+ * }
378
+ *
379
+ * doesTypeExist(type: string): boolean {
380
+ * if (AbstractSchemas.has(type)) {
381
+ * return true;
382
+ * }
383
+ * return this._schema.doesTypeExist(type);
384
+ * }
385
+ *
386
+ * attributesDefinitionFor(identifier: RecordIdentifier | { type: string }): AttributesSchema {
387
+ * return this._schema.attributesDefinitionFor(identifier);
388
+ * }
389
+ *
390
+ * relationshipsDefinitionFor(identifier: RecordIdentifier | { type: string }): RelationshipsSchema {
391
+ * const schema = AbstractSchemas.get(identifier.type);
392
+ * return schema || this._schema.relationshipsDefinitionFor(identifier);
393
+ * }
394
+ * }
395
+ *
396
+ * export default class extends Store {
397
+ * constructor(...args) {
398
+ * super(...args);
399
+ *
400
+ * const schema = this.schema;
401
+ * this.registerSchema(new SchemaDelegator(schema));
402
+ * }
403
+ * }
404
+ * ```
405
+ *
406
+ * @method registerSchema
407
+ * @param {SchemaService} schema
408
+ * @public
409
+ */
410
+ registerSchema(schema: SchemaService): void;
411
+ /**
412
+ Returns the schema for a particular resource type (modelName).
413
+
414
+ When used with Model from @ember-data/model the return is the model class,
415
+ but this is not guaranteed.
416
+
417
+ If looking to query attribute or relationship information it is
418
+ recommended to use `getSchemaDefinitionService` instead. This method
419
+ should be considered legacy and exists primarily to continue to support
420
+ Adapter/Serializer APIs which expect it's return value in their method
421
+ signatures.
422
+
423
+ The class of a model might be useful if you want to get a list of all the
424
+ relationship names of the model, see
425
+ [`relationshipNames`](/ember-data/release/classes/Model?anchor=relationshipNames)
426
+ for example.
427
+
428
+ @method modelFor
429
+ @public
430
+ @param {string} type
431
+ @return {ModelSchema}
432
+ */
433
+ modelFor<T>(type: TypeFromInstance<T>): ModelSchema<T>;
434
+ modelFor(type: string): ModelSchema;
435
+ /**
436
+ Create a new record in the current store. The properties passed
437
+ to this method are set on the newly created record.
438
+
439
+ To create a new instance of a `Post`:
440
+
441
+ ```js
442
+ store.createRecord('post', {
443
+ title: 'Ember is awesome!'
444
+ });
445
+ ```
446
+
447
+ To create a new instance of a `Post` that has a relationship with a `User` record:
448
+
449
+ ```js
450
+ let user = this.store.peekRecord('user', 1);
451
+ store.createRecord('post', {
452
+ title: 'Ember is awesome!',
453
+ user: user
454
+ });
455
+ ```
456
+
457
+ @method createRecord
458
+ @public
459
+ @param {String} type the name of the resource
460
+ @param {Object} inputProperties a hash of properties to set on the
461
+ newly created record.
462
+ @return {Model} record
463
+ */
464
+ createRecord<T>(type: TypeFromInstance<T>, inputProperties: CreateRecordProperties<T>): T;
465
+ createRecord(type: string, inputProperties: CreateRecordProperties): OpaqueRecordInstance;
466
+ /**
467
+ For symmetry, a record can be deleted via the store.
468
+
469
+ Example
470
+
471
+ ```javascript
472
+ let post = store.createRecord('post', {
473
+ title: 'Ember is awesome!'
474
+ });
475
+
476
+ store.deleteRecord(post);
477
+ ```
478
+
479
+ @method deleteRecord
480
+ @public
481
+ @param {unknown} record
482
+ */
483
+ deleteRecord<T>(record: T): void;
484
+ /**
485
+ For symmetry, a record can be unloaded via the store.
486
+ This will cause the record to be destroyed and freed up for garbage collection.
487
+
488
+ Example
489
+
490
+ ```javascript
491
+ store.findRecord('post', 1).then(function(post) {
492
+ store.unloadRecord(post);
493
+ });
494
+ ```
495
+
496
+ @method unloadRecord
497
+ @public
498
+ @param {Model} record
499
+ */
500
+ unloadRecord<T>(record: T): void;
501
+ /**
502
+ This method returns a record for a given identifier or type and id combination.
503
+
504
+ The `findRecord` method will always resolve its promise with the same
505
+ object for a given identifier or type and `id`.
506
+
507
+ The `findRecord` method will always return a **promise** that will be
508
+ resolved with the record.
509
+
510
+ **Example 1**
511
+
512
+ ```app/routes/post.js
513
+ import Route from '@ember/routing/route';
514
+
515
+ export default class PostRoute extends Route {
516
+ model({ post_id }) {
517
+ return this.store.findRecord('post', post_id);
518
+ }
519
+ }
520
+ ```
521
+
522
+ **Example 2**
523
+
524
+ `findRecord` can be called with a single identifier argument instead of the combination
525
+ of `type` (modelName) and `id` as separate arguments. You may recognize this combo as
526
+ the typical pairing from [JSON:API](https://jsonapi.org/format/#document-resource-object-identification)
527
+
528
+ ```app/routes/post.js
529
+ import Route from '@ember/routing/route';
530
+
531
+ export default class PostRoute extends Route {
532
+ model({ post_id: id }) {
533
+ return this.store.findRecord({ type: 'post', id });
534
+ }
535
+ }
536
+ ```
537
+
538
+ **Example 3**
539
+
540
+ If you have previously received an lid via an Identifier for this record, and the record
541
+ has already been assigned an id, you can find the record again using just the lid.
542
+
543
+ ```app/routes/post.js
544
+ store.findRecord({ lid });
545
+ ```
546
+
547
+ If the record is not yet available, the store will ask the adapter's `findRecord`
548
+ method to retrieve and supply the necessary data. If the record is already present
549
+ in the store, it depends on the reload behavior _when_ the returned promise
550
+ resolves.
551
+
552
+ ### Preloading
553
+
554
+ You can optionally `preload` specific attributes and relationships that you know of
555
+ by passing them via the passed `options`.
556
+
557
+ For example, if your Ember route looks like `/posts/1/comments/2` and your API route
558
+ for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment
559
+ without also fetching the post you can pass in the post to the `findRecord` call:
560
+
561
+ ```app/routes/post-comments.js
562
+ import Route from '@ember/routing/route';
563
+
564
+ export default class PostRoute extends Route {
565
+ model({ post_id, comment_id: id }) {
566
+ return this.store.findRecord({ type: 'comment', id, { preload: { post: post_id }} });
567
+ }
568
+ }
569
+ ```
570
+
571
+ In your adapter you can then access this id without triggering a network request via the
572
+ snapshot:
573
+
574
+ ```app/adapters/application.js
575
+ export default class Adapter {
576
+
577
+ findRecord(store, schema, id, snapshot) {
578
+ let type = schema.modelName;
579
+
580
+ if (type === 'comment')
581
+ let postId = snapshot.belongsTo('post', { id: true });
582
+
583
+ return fetch(`./posts/${postId}/comments/${id}`)
584
+ .then(response => response.json())
585
+ }
586
+ }
587
+
588
+ static create() {
589
+ return new this();
590
+ }
591
+ }
592
+ ```
593
+
594
+ This could also be achieved by supplying the post id to the adapter via the adapterOptions
595
+ property on the options hash.
596
+
597
+ ```app/routes/post-comments.js
598
+ import Route from '@ember/routing/route';
599
+
600
+ export default class PostRoute extends Route {
601
+ model({ post_id, comment_id: id }) {
602
+ return this.store.findRecord({ type: 'comment', id, { adapterOptions: { post: post_id }} });
603
+ }
604
+ }
605
+ ```
606
+
607
+ ```app/adapters/application.js
608
+ export default class Adapter {
609
+ findRecord(store, schema, id, snapshot) {
610
+ let type = schema.modelName;
611
+
612
+ if (type === 'comment')
613
+ let postId = snapshot.adapterOptions.post;
614
+
615
+ return fetch(`./posts/${postId}/comments/${id}`)
616
+ .then(response => response.json())
617
+ }
618
+ }
619
+
620
+ static create() {
621
+ return new this();
622
+ }
623
+ }
624
+ ```
625
+
626
+ If you have access to the post model you can also pass the model itself to preload:
627
+
628
+ ```javascript
629
+ let post = await store.findRecord('post', 1);
630
+ let comment = await store.findRecord('comment', 2, { post: myPostModel });
631
+ ```
632
+
633
+ ### Reloading
634
+
635
+ The reload behavior is configured either via the passed `options` hash or
636
+ the result of the adapter's `shouldReloadRecord`.
637
+
638
+ If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates
639
+ to `true`, then the returned promise resolves once the adapter returns
640
+ data, regardless if the requested record is already in the store:
641
+
642
+ ```js
643
+ store.push({
644
+ data: {
645
+ id: 1,
646
+ type: 'post',
647
+ revision: 1
648
+ }
649
+ });
650
+
651
+ // adapter#findRecord resolves with
652
+ // [
653
+ // {
654
+ // id: 1,
655
+ // type: 'post',
656
+ // revision: 2
657
+ // }
658
+ // ]
659
+ store.findRecord('post', 1, { reload: true }).then(function(post) {
660
+ post.revision; // 2
661
+ });
662
+ ```
663
+
664
+ If no reload is indicated via the above mentioned ways, then the promise
665
+ immediately resolves with the cached version in the store.
666
+
667
+ ### Background Reloading
668
+
669
+ Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`,
670
+ then a background reload is started, which updates the records' data, once
671
+ it is available:
672
+
673
+ ```js
674
+ // app/adapters/post.js
675
+ import ApplicationAdapter from "./application";
676
+
677
+ export default class PostAdapter extends ApplicationAdapter {
678
+ shouldReloadRecord(store, snapshot) {
679
+ return false;
680
+ },
681
+
682
+ shouldBackgroundReloadRecord(store, snapshot) {
683
+ return true;
684
+ }
685
+ });
686
+
687
+ // ...
688
+
689
+ store.push({
690
+ data: {
691
+ id: 1,
692
+ type: 'post',
693
+ revision: 1
694
+ }
695
+ });
696
+
697
+ let blogPost = store.findRecord('post', 1).then(function(post) {
698
+ post.revision; // 1
699
+ });
700
+
701
+ // later, once adapter#findRecord resolved with
702
+ // [
703
+ // {
704
+ // id: 1,
705
+ // type: 'post',
706
+ // revision: 2
707
+ // }
708
+ // ]
709
+
710
+ blogPost.revision; // 2
711
+ ```
712
+
713
+ If you would like to force or prevent background reloading, you can set a
714
+ boolean value for `backgroundReload` in the options object for
715
+ `findRecord`.
716
+
717
+ ```app/routes/post/edit.js
718
+ import Route from '@ember/routing/route';
719
+
720
+ export default class PostEditRoute extends Route {
721
+ model(params) {
722
+ return this.store.findRecord('post', params.post_id, { backgroundReload: false });
723
+ }
724
+ }
725
+ ```
726
+
727
+ If you pass an object on the `adapterOptions` property of the options
728
+ argument it will be passed to your adapter via the snapshot
729
+
730
+ ```app/routes/post/edit.js
731
+ import Route from '@ember/routing/route';
732
+
733
+ export default class PostEditRoute extends Route {
734
+ model(params) {
735
+ return this.store.findRecord('post', params.post_id, {
736
+ adapterOptions: { subscribe: false }
737
+ });
738
+ }
739
+ }
740
+ ```
741
+
742
+ ```app/adapters/post.js
743
+ import MyCustomAdapter from './custom-adapter';
744
+
745
+ export default class PostAdapter extends MyCustomAdapter {
746
+ findRecord(store, type, id, snapshot) {
747
+ if (snapshot.adapterOptions.subscribe) {
748
+ // ...
749
+ }
750
+ // ...
751
+ }
752
+ }
753
+ ```
754
+
755
+ See [peekRecord](../methods/peekRecord?anchor=peekRecord) to get the cached version of a record.
756
+
757
+ ### Retrieving Related Model Records
758
+
759
+ If you use an adapter such as Ember's default
760
+ [`JSONAPIAdapter`](/ember-data/release/classes/JSONAPIAdapter)
761
+ that supports the [JSON API specification](http://jsonapi.org/) and if your server
762
+ endpoint supports the use of an
763
+ ['include' query parameter](http://jsonapi.org/format/#fetching-includes),
764
+ you can use `findRecord()` or `findAll()` to automatically retrieve additional records related to
765
+ the one you request by supplying an `include` parameter in the `options` object.
766
+
767
+ For example, given a `post` model that has a `hasMany` relationship with a `comment`
768
+ model, when we retrieve a specific post we can have the server also return that post's
769
+ comments in the same request:
770
+
771
+ ```app/routes/post.js
772
+ import Route from '@ember/routing/route';
773
+
774
+ export default class PostRoute extends Route {
775
+ model(params) {
776
+ return this.store.findRecord('post', params.post_id, { include: 'comments' });
777
+ }
778
+ }
779
+ ```
780
+
781
+ ```app/adapters/application.js
782
+ export default class Adapter {
783
+ findRecord(store, schema, id, snapshot) {
784
+ let type = schema.modelName;
785
+
786
+ if (type === 'post')
787
+ let includes = snapshot.adapterOptions.include;
788
+
789
+ return fetch(`./posts/${postId}?include=${includes}`)
790
+ .then(response => response.json())
791
+ }
792
+ }
793
+
794
+ static create() {
795
+ return new this();
796
+ }
797
+ }
798
+ ```
799
+
800
+ In this case, the post's comments would then be available in your template as
801
+ `model.comments`.
802
+
803
+ Multiple relationships can be requested using an `include` parameter consisting of a
804
+ comma-separated list (without white-space) while nested relationships can be specified
805
+ using a dot-separated sequence of relationship names. So to request both the post's
806
+ comments and the authors of those comments the request would look like this:
807
+
808
+ ```app/routes/post.js
809
+ import Route from '@ember/routing/route';
810
+
811
+ export default class PostRoute extends Route {
812
+ model(params) {
813
+ return this.store.findRecord('post', params.post_id, { include: 'comments,comments.author' });
814
+ }
815
+ }
816
+ ```
817
+
818
+ ### Retrieving Specific Fields by Type
819
+
820
+ If your server endpoint supports the use of a ['fields' query parameter](https://jsonapi.org/format/#fetching-sparse-fieldsets),
821
+ you can use pass those fields through to your server. At this point in time, this requires a few manual steps on your part.
822
+
823
+ 1. Implement `buildQuery` in your adapter.
824
+
825
+ ```app/adapters/application.js
826
+ buildQuery(snapshot) {
827
+ let query = super.buildQuery(...arguments);
828
+
829
+ let { fields } = snapshot.adapterOptions;
830
+
831
+ if (fields) {
832
+ query.fields = fields;
833
+ }
834
+
835
+ return query;
836
+ }
837
+ ```
838
+
839
+ 2. Then pass through the applicable fields to your `findRecord` request.
840
+
841
+ Given a `post` model with attributes body, title, publishDate and meta, you can retrieve a filtered list of attributes.
842
+
843
+ ```app/routes/post.js
844
+ import Route from '@ember/routing/route';
845
+ export default Route.extend({
846
+ model(params) {
847
+ return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title' } });
848
+ }
849
+ });
850
+ ```
851
+
852
+ Moreover, you can filter attributes on related models as well. If a `post` has a `belongsTo` relationship to a user,
853
+ just include the relationship key and attributes.
854
+
855
+ ```app/routes/post.js
856
+ import Route from '@ember/routing/route';
857
+ export default Route.extend({
858
+ model(params) {
859
+ return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title', user: 'name,email' } });
860
+ }
861
+ });
862
+ ```
863
+
864
+ @since 1.13.0
865
+ @method findRecord
866
+ @public
867
+ @param {String|object} type - either a string representing the name of the resource or a ResourceIdentifier object containing both the type (a string) and the id (a string) for the record or an lid (a string) of an existing record
868
+ @param {(String|Integer|Object)} id - optional object with options for the request only if the first param is a ResourceIdentifier, else the string id of the record to be retrieved
869
+ @param {Object} [options] - if the first param is a string this will be the optional options for the request. See examples for available options.
870
+ @return {Promise} promise
871
+ */
872
+ findRecord<T>(resource: TypeFromInstance<T>, id: string | number, options?: FindRecordOptions): Promise<T>;
873
+ findRecord(resource: string, id: string | number, options?: FindRecordOptions): Promise<unknown>;
874
+ findRecord<T>(resource: ResourceIdentifierObject<TypeFromInstance<T>>, id?: FindRecordOptions): Promise<T>;
875
+ findRecord(resource: ResourceIdentifierObject, id?: FindRecordOptions): Promise<unknown>;
876
+ /**
877
+ Get the reference for the specified record.
878
+
879
+ Example
880
+
881
+ ```javascript
882
+ let userRef = store.getReference('user', 1);
883
+
884
+ // check if the user is loaded
885
+ let isLoaded = userRef.value() !== null;
886
+
887
+ // get the record of the reference (null if not yet available)
888
+ let user = userRef.value();
889
+
890
+ // get the identifier of the reference
891
+ if (userRef.remoteType() === 'id') {
892
+ let id = userRef.id();
893
+ }
894
+
895
+ // load user (via store.find)
896
+ userRef.load().then(...)
897
+
898
+ // or trigger a reload
899
+ userRef.reload().then(...)
900
+
901
+ // provide data for reference
902
+ userRef.push({ id: 1, username: '@user' }).then(function(user) {
903
+ userRef.value() === user;
904
+ });
905
+ ```
906
+
907
+ @method getReference
908
+ @public
909
+ @param {String|object} resource - modelName (string) or Identifier (object)
910
+ @param {String|Integer} id
911
+ @since 2.5.0
912
+ @return {RecordReference}
913
+ */
914
+ getReference(resource: string | ResourceIdentifierObject, id: string | number): RecordReference;
915
+ /**
916
+ Get a record by a given type and ID without triggering a fetch.
917
+
918
+ This method will synchronously return the record if it is available in the store,
919
+ otherwise it will return `null`. A record is available if it has been fetched earlier, or
920
+ pushed manually into the store.
921
+
922
+ See [findRecord](../methods/findRecord?anchor=findRecord) if you would like to request this record from the backend.
923
+
924
+ _Note: This is a synchronous method and does not return a promise._
925
+
926
+ **Example 1**
927
+
928
+ ```js
929
+ let post = store.peekRecord('post', 1);
930
+
931
+ post.id; // 1
932
+ ```
933
+
934
+ `peekRecord` can be called with a single identifier argument instead of the combination
935
+ of `type` (modelName) and `id` as separate arguments. You may recognize this combo as
936
+ the typical pairing from [JSON:API](https://jsonapi.org/format/#document-resource-object-identification)
937
+
938
+ **Example 2**
939
+
940
+ ```js
941
+ let post = store.peekRecord({ type: 'post', id });
942
+ post.id; // 1
943
+ ```
944
+
945
+ If you have previously received an lid from an Identifier for this record, you can lookup the record again using
946
+ just the lid.
947
+
948
+ **Example 3**
949
+
950
+ ```js
951
+ let post = store.peekRecord({ lid });
952
+ post.id; // 1
953
+ ```
954
+
955
+
956
+ @since 1.13.0
957
+ @method peekRecord
958
+ @public
959
+ @param {String|object} modelName - either a string representing the modelName or a ResourceIdentifier object containing both the type (a string) and the id (a string) for the record or an lid (a string) of an existing record
960
+ @param {String|Integer} id - optional only if the first param is a ResourceIdentifier, else the string id of the record to be retrieved.
961
+ @return {Model|null} record
962
+ */
963
+ peekRecord<T = OpaqueRecordInstance>(identifier: string, id: string | number): T | null;
964
+ peekRecord<T = OpaqueRecordInstance>(identifier: ResourceIdentifierObject): T | null;
965
+ /**
966
+ This method delegates a query to the adapter. This is the one place where
967
+ adapter-level semantics are exposed to the application.
968
+
969
+ Each time this method is called a new request is made through the adapter.
970
+
971
+ Exposing queries this way seems preferable to creating an abstract query
972
+ language for all server-side queries, and then require all adapters to
973
+ implement them.
974
+
975
+ ---
976
+
977
+ If you do something like this:
978
+
979
+ ```javascript
980
+ store.query('person', { page: 1 });
981
+ ```
982
+
983
+ The request made to the server will look something like this:
984
+
985
+ ```
986
+ GET "/api/v1/person?page=1"
987
+ ```
988
+
989
+ ---
990
+
991
+ If you do something like this:
992
+
993
+ ```javascript
994
+ store.query('person', { ids: [1, 2, 3] });
995
+ ```
996
+
997
+ The request made to the server will look something like this:
998
+
999
+ ```
1000
+ GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3"
1001
+ decoded: "/api/v1/person?ids[]=1&ids[]=2&ids[]=3"
1002
+ ```
1003
+
1004
+ This method returns a promise, which is resolved with a
1005
+ [`Collection`](/ember-data/release/classes/Collection)
1006
+ once the server returns.
1007
+
1008
+ @since 1.13.0
1009
+ @method query
1010
+ @public
1011
+ @param {String} type the name of the resource
1012
+ @param {object} query a query to be used by the adapter
1013
+ @param {Object} options optional, may include `adapterOptions` hash which will be passed to adapter.query
1014
+ @return {Promise} promise
1015
+ */
1016
+ query<T>(type: TypeFromInstance<T>, query: Record<string, unknown>, options?: QueryOptions): Promise<Collection<T>>;
1017
+ query(type: string, query: Record<string, unknown>, options?: QueryOptions): Promise<Collection>;
1018
+ /**
1019
+ This method makes a request for one record, where the `id` is not known
1020
+ beforehand (if the `id` is known, use [`findRecord`](../methods/findRecord?anchor=findRecord)
1021
+ instead).
1022
+
1023
+ This method can be used when it is certain that the server will return a
1024
+ single object for the primary data.
1025
+
1026
+ Each time this method is called a new request is made through the adapter.
1027
+
1028
+ Let's assume our API provides an endpoint for the currently logged in user
1029
+ via:
1030
+
1031
+ ```
1032
+ // GET /api/current_user
1033
+ {
1034
+ user: {
1035
+ id: 1234,
1036
+ username: 'admin'
1037
+ }
1038
+ }
1039
+ ```
1040
+
1041
+ Since the specific `id` of the `user` is not known beforehand, we can use
1042
+ `queryRecord` to get the user:
1043
+
1044
+ ```javascript
1045
+ store.queryRecord('user', {}).then(function(user) {
1046
+ let username = user.username;
1047
+ // do thing
1048
+ });
1049
+ ```
1050
+
1051
+ The request is made through the adapters' `queryRecord`:
1052
+
1053
+ ```app/adapters/user.js
1054
+ import Adapter from '@ember-data/adapter';
1055
+ import $ from 'jquery';
1056
+
1057
+ export default class UserAdapter extends Adapter {
1058
+ queryRecord(modelName, query) {
1059
+ return $.getJSON('/api/current_user');
1060
+ }
1061
+ }
1062
+ ```
1063
+
1064
+ Note: the primary use case for `store.queryRecord` is when a single record
1065
+ is queried and the `id` is not known beforehand. In all other cases
1066
+ `store.query` and using the first item of the array is likely the preferred
1067
+ way:
1068
+
1069
+ ```
1070
+ // GET /users?username=unique
1071
+ {
1072
+ data: [{
1073
+ id: 1234,
1074
+ type: 'user',
1075
+ attributes: {
1076
+ username: "unique"
1077
+ }
1078
+ }]
1079
+ }
1080
+ ```
1081
+
1082
+ ```javascript
1083
+ store.query('user', { username: 'unique' }).then(function(users) {
1084
+ return users.firstObject;
1085
+ }).then(function(user) {
1086
+ let id = user.id;
1087
+ });
1088
+ ```
1089
+
1090
+ This method returns a promise, which resolves with the found record.
1091
+
1092
+ If the adapter returns no data for the primary data of the payload, then
1093
+ `queryRecord` resolves with `null`:
1094
+
1095
+ ```
1096
+ // GET /users?username=unique
1097
+ {
1098
+ data: null
1099
+ }
1100
+ ```
1101
+
1102
+ ```javascript
1103
+ store.queryRecord('user', { username: 'unique' }).then(function(user) {
1104
+ // user is null
1105
+ });
1106
+ ```
1107
+
1108
+ @since 1.13.0
1109
+ @method queryRecord
1110
+ @public
1111
+ @param {String} modelName
1112
+ @param {any} query an opaque query to be used by the adapter
1113
+ @param {Object} options optional, may include `adapterOptions` hash which will be passed to adapter.queryRecord
1114
+ @return {Promise} promise which resolves with the found record or `null`
1115
+ */
1116
+ queryRecord(modelName: string, query: Record<string, unknown>, options?: QueryOptions): Promise<OpaqueRecordInstance | null>;
1117
+ /**
1118
+ `findAll` asks the adapter's `findAll` method to find the records for the
1119
+ given type, and returns a promise which will resolve with all records of
1120
+ this type present in the store, even if the adapter only returns a subset
1121
+ of them.
1122
+
1123
+ ```app/routes/authors.js
1124
+ import Route from '@ember/routing/route';
1125
+
1126
+ export default class AuthorsRoute extends Route {
1127
+ model(params) {
1128
+ return this.store.findAll('author');
1129
+ }
1130
+ }
1131
+ ```
1132
+
1133
+ _When_ the returned promise resolves depends on the reload behavior,
1134
+ configured via the passed `options` hash and the result of the adapter's
1135
+ `shouldReloadAll` method.
1136
+
1137
+ ### Reloading
1138
+
1139
+ If `{ reload: true }` is passed or `adapter.shouldReloadAll` evaluates to
1140
+ `true`, then the returned promise resolves once the adapter returns data,
1141
+ regardless if there are already records in the store:
1142
+
1143
+ ```js
1144
+ store.push({
1145
+ data: {
1146
+ id: 'first',
1147
+ type: 'author'
1148
+ }
1149
+ });
1150
+
1151
+ // adapter#findAll resolves with
1152
+ // [
1153
+ // {
1154
+ // id: 'second',
1155
+ // type: 'author'
1156
+ // }
1157
+ // ]
1158
+ store.findAll('author', { reload: true }).then(function(authors) {
1159
+ authors.getEach('id'); // ['first', 'second']
1160
+ });
1161
+ ```
1162
+
1163
+ If no reload is indicated via the above mentioned ways, then the promise
1164
+ immediately resolves with all the records currently loaded in the store.
1165
+
1166
+ ### Background Reloading
1167
+
1168
+ Optionally, if `adapter.shouldBackgroundReloadAll` evaluates to `true`,
1169
+ then a background reload is started. Once this resolves, the array with
1170
+ which the promise resolves, is updated automatically so it contains all the
1171
+ records in the store:
1172
+
1173
+ ```app/adapters/application.js
1174
+ import Adapter from '@ember-data/adapter';
1175
+
1176
+ export default class ApplicationAdapter extends Adapter {
1177
+ shouldReloadAll(store, snapshotsArray) {
1178
+ return false;
1179
+ },
1180
+
1181
+ shouldBackgroundReloadAll(store, snapshotsArray) {
1182
+ return true;
1183
+ }
1184
+ });
1185
+
1186
+ // ...
1187
+
1188
+ store.push({
1189
+ data: {
1190
+ id: 'first',
1191
+ type: 'author'
1192
+ }
1193
+ });
1194
+
1195
+ let allAuthors;
1196
+ store.findAll('author').then(function(authors) {
1197
+ authors.getEach('id'); // ['first']
1198
+
1199
+ allAuthors = authors;
1200
+ });
1201
+
1202
+ // later, once adapter#findAll resolved with
1203
+ // [
1204
+ // {
1205
+ // id: 'second',
1206
+ // type: 'author'
1207
+ // }
1208
+ // ]
1209
+
1210
+ allAuthors.getEach('id'); // ['first', 'second']
1211
+ ```
1212
+
1213
+ If you would like to force or prevent background reloading, you can set a
1214
+ boolean value for `backgroundReload` in the options object for
1215
+ `findAll`.
1216
+
1217
+ ```app/routes/post/edit.js
1218
+ import Route from '@ember/routing/route';
1219
+
1220
+ export default class PostEditRoute extends Route {
1221
+ model() {
1222
+ return this.store.findAll('post', { backgroundReload: false });
1223
+ }
1224
+ }
1225
+ ```
1226
+
1227
+ If you pass an object on the `adapterOptions` property of the options
1228
+ argument it will be passed to you adapter via the `snapshotRecordArray`
1229
+
1230
+ ```app/routes/posts.js
1231
+ import Route from '@ember/routing/route';
1232
+
1233
+ export default class PostsRoute extends Route {
1234
+ model(params) {
1235
+ return this.store.findAll('post', {
1236
+ adapterOptions: { subscribe: false }
1237
+ });
1238
+ }
1239
+ }
1240
+ ```
1241
+
1242
+ ```app/adapters/post.js
1243
+ import MyCustomAdapter from './custom-adapter';
1244
+
1245
+ export default class UserAdapter extends MyCustomAdapter {
1246
+ findAll(store, type, sinceToken, snapshotRecordArray) {
1247
+ if (snapshotRecordArray.adapterOptions.subscribe) {
1248
+ // ...
1249
+ }
1250
+ // ...
1251
+ }
1252
+ }
1253
+ ```
1254
+
1255
+ See [peekAll](../methods/peekAll?anchor=peekAll) to get an array of current records in the
1256
+ store, without waiting until a reload is finished.
1257
+
1258
+ ### Retrieving Related Model Records
1259
+
1260
+ If you use an adapter such as Ember's default
1261
+ [`JSONAPIAdapter`](/ember-data/release/classes/JSONAPIAdapter)
1262
+ that supports the [JSON API specification](http://jsonapi.org/) and if your server
1263
+ endpoint supports the use of an
1264
+ ['include' query parameter](http://jsonapi.org/format/#fetching-includes),
1265
+ you can use `findAll()` to automatically retrieve additional records related to
1266
+ those requested by supplying an `include` parameter in the `options` object.
1267
+
1268
+ For example, given a `post` model that has a `hasMany` relationship with a `comment`
1269
+ model, when we retrieve all of the post records we can have the server also return
1270
+ all of the posts' comments in the same request:
1271
+
1272
+ ```app/routes/posts.js
1273
+ import Route from '@ember/routing/route';
1274
+
1275
+ export default class PostsRoute extends Route {
1276
+ model() {
1277
+ return this.store.findAll('post', { include: 'comments' });
1278
+ }
1279
+ }
1280
+ ```
1281
+ Multiple relationships can be requested using an `include` parameter consisting of a
1282
+ comma-separated list (without white-space) while nested relationships can be specified
1283
+ using a dot-separated sequence of relationship names. So to request both the posts'
1284
+ comments and the authors of those comments the request would look like this:
1285
+
1286
+ ```app/routes/posts.js
1287
+ import Route from '@ember/routing/route';
1288
+
1289
+ export default class PostsRoute extends Route {
1290
+ model() {
1291
+ return this.store.findAll('post', { include: 'comments,comments.author' });
1292
+ }
1293
+ }
1294
+ ```
1295
+
1296
+ See [query](../methods/query?anchor=query) to only get a subset of records from the server.
1297
+
1298
+ @since 1.13.0
1299
+ @method findAll
1300
+ @public
1301
+ @param {string} type the name of the resource
1302
+ @param {object} options
1303
+ @return {Promise} promise
1304
+ */
1305
+ findAll<T>(type: TypeFromInstance<T>, options?: FindAllOptions): Promise<IdentifierArray<T>>;
1306
+ findAll(type: string, options?: FindAllOptions): Promise<IdentifierArray>;
1307
+ /**
1308
+ This method returns a filtered array that contains all of the
1309
+ known records for a given type in the store.
1310
+
1311
+ Note that because it's just a filter, the result will contain any
1312
+ locally created records of the type, however, it will not make a
1313
+ request to the backend to retrieve additional records. If you
1314
+ would like to request all the records from the backend please use
1315
+ [store.findAll](../methods/findAll?anchor=findAll).
1316
+
1317
+ Also note that multiple calls to `peekAll` for a given type will always
1318
+ return the same `RecordArray`.
1319
+
1320
+ Example
1321
+
1322
+ ```javascript
1323
+ let localPosts = store.peekAll('post');
1324
+ ```
1325
+
1326
+ @since 1.13.0
1327
+ @method peekAll
1328
+ @public
1329
+ @param {string} type the name of the resource
1330
+ @return {RecordArray}
1331
+ */
1332
+ peekAll<T>(type: TypeFromInstance<T>): IdentifierArray<T>;
1333
+ peekAll(type: string): IdentifierArray;
1334
+ /**
1335
+ This method unloads all records in the store.
1336
+ It schedules unloading to happen during the next run loop.
1337
+
1338
+ Optionally you can pass a type which unload all records for a given type.
1339
+
1340
+ ```javascript
1341
+ store.unloadAll();
1342
+ store.unloadAll('post');
1343
+ ```
1344
+
1345
+ @method unloadAll
1346
+ @param {string} type the name of the resource
1347
+ @public
1348
+ */
1349
+ unloadAll<T>(type: TypeFromInstance<T>): void;
1350
+ unloadAll(type?: string): void;
1351
+ /**
1352
+ Push some data for a given type into the store.
1353
+
1354
+ This method expects normalized [JSON API](http://jsonapi.org/) document. This means you have to follow [JSON API specification](http://jsonapi.org/format/) with few minor adjustments:
1355
+ - record's `type` should always be in singular, dasherized form
1356
+ - members (properties) should be camelCased
1357
+
1358
+ [Your primary data should be wrapped inside `data` property](http://jsonapi.org/format/#document-top-level):
1359
+
1360
+ ```js
1361
+ store.push({
1362
+ data: {
1363
+ // primary data for single record of type `Person`
1364
+ id: '1',
1365
+ type: 'person',
1366
+ attributes: {
1367
+ firstName: 'Daniel',
1368
+ lastName: 'Kmak'
1369
+ }
1370
+ }
1371
+ });
1372
+ ```
1373
+
1374
+ [Demo.](http://ember-twiddle.com/fb99f18cd3b4d3e2a4c7)
1375
+
1376
+ `data` property can also hold an array (of records):
1377
+
1378
+ ```js
1379
+ store.push({
1380
+ data: [
1381
+ // an array of records
1382
+ {
1383
+ id: '1',
1384
+ type: 'person',
1385
+ attributes: {
1386
+ firstName: 'Daniel',
1387
+ lastName: 'Kmak'
1388
+ }
1389
+ },
1390
+ {
1391
+ id: '2',
1392
+ type: 'person',
1393
+ attributes: {
1394
+ firstName: 'Tom',
1395
+ lastName: 'Dale'
1396
+ }
1397
+ }
1398
+ ]
1399
+ });
1400
+ ```
1401
+
1402
+ [Demo.](http://ember-twiddle.com/69cdbeaa3702159dc355)
1403
+
1404
+ There are some typical properties for `JSONAPI` payload:
1405
+ * `id` - mandatory, unique record's key
1406
+ * `type` - mandatory string which matches `model`'s dasherized name in singular form
1407
+ * `attributes` - object which holds data for record attributes - `attr`'s declared in model
1408
+ * `relationships` - object which must contain any of the following properties under each relationships' respective key (example path is `relationships.achievements.data`):
1409
+ - [`links`](http://jsonapi.org/format/#document-links)
1410
+ - [`data`](http://jsonapi.org/format/#document-resource-object-linkage) - place for primary data
1411
+ - [`meta`](http://jsonapi.org/format/#document-meta) - object which contains meta-information about relationship
1412
+
1413
+ For this model:
1414
+
1415
+ ```app/models/person.js
1416
+ import Model, { attr, hasMany } from '@ember-data/model';
1417
+
1418
+ export default class PersonRoute extends Route {
1419
+ @attr('string') firstName;
1420
+ @attr('string') lastName;
1421
+
1422
+ @hasMany('person') children;
1423
+ }
1424
+ ```
1425
+
1426
+ To represent the children as IDs:
1427
+
1428
+ ```js
1429
+ {
1430
+ data: {
1431
+ id: '1',
1432
+ type: 'person',
1433
+ attributes: {
1434
+ firstName: 'Tom',
1435
+ lastName: 'Dale'
1436
+ },
1437
+ relationships: {
1438
+ children: {
1439
+ data: [
1440
+ {
1441
+ id: '2',
1442
+ type: 'person'
1443
+ },
1444
+ {
1445
+ id: '3',
1446
+ type: 'person'
1447
+ },
1448
+ {
1449
+ id: '4',
1450
+ type: 'person'
1451
+ }
1452
+ ]
1453
+ }
1454
+ }
1455
+ }
1456
+ }
1457
+ ```
1458
+
1459
+ [Demo.](http://ember-twiddle.com/343e1735e034091f5bde)
1460
+
1461
+ To represent the children relationship as a URL:
1462
+
1463
+ ```js
1464
+ {
1465
+ data: {
1466
+ id: '1',
1467
+ type: 'person',
1468
+ attributes: {
1469
+ firstName: 'Tom',
1470
+ lastName: 'Dale'
1471
+ },
1472
+ relationships: {
1473
+ children: {
1474
+ links: {
1475
+ related: '/people/1/children'
1476
+ }
1477
+ }
1478
+ }
1479
+ }
1480
+ }
1481
+ ```
1482
+
1483
+ If you're streaming data or implementing an adapter, make sure
1484
+ that you have converted the incoming data into this form. The
1485
+ store's [normalize](../methods/normalize?anchor=normalize) method is a convenience
1486
+ helper for converting a json payload into the form Ember Data
1487
+ expects.
1488
+
1489
+ ```js
1490
+ store.push(store.normalize('person', data));
1491
+ ```
1492
+
1493
+ This method can be used both to push in brand new
1494
+ records, as well as to update existing records.
1495
+
1496
+ @method push
1497
+ @public
1498
+ @param {Object} data
1499
+ @return the record(s) that was created or
1500
+ updated.
1501
+ */
1502
+ push(data: EmptyResourceDocument): null;
1503
+ push<T>(data: SingleResourceDocument<TypeFromInstance<T>>): T;
1504
+ push(data: SingleResourceDocument): OpaqueRecordInstance;
1505
+ push<T>(data: CollectionResourceDocument<TypeFromInstance<T>>): T[];
1506
+ push(data: CollectionResourceDocument): OpaqueRecordInstance[];
1507
+ /**
1508
+ Push some data in the form of a json-api document into the store,
1509
+ without creating materialized records.
1510
+
1511
+ @method _push
1512
+ @private
1513
+ @param {Object} jsonApiDoc
1514
+ @return {StableRecordIdentifier|Array<StableRecordIdentifier>|null} identifiers for the primary records that had data loaded
1515
+ */
1516
+ _push(jsonApiDoc: JsonApiDocument, asyncFlush?: boolean): StableExistingRecordIdentifier | StableExistingRecordIdentifier[] | null;
1517
+ /**
1518
+ * Trigger a save for a Record.
1519
+ *
1520
+ * Returns a promise resolving with the same record when the save is complete.
1521
+ *
1522
+ * @method saveRecord
1523
+ * @public
1524
+ * @param {unknown} record
1525
+ * @param options
1526
+ * @return {Promise<record>}
1527
+ */
1528
+ saveRecord<T>(record: T, options?: Record<string, unknown>): Promise<T>;
1529
+ /**
1530
+ * Instantiation hook allowing applications or addons to configure the store
1531
+ * to utilize a custom Cache implementation.
1532
+ *
1533
+ * This hook should not be called directly by consuming applications or libraries.
1534
+ * Use `Store.cache` to access the Cache instance.
1535
+ *
1536
+ * @method createCache (hook)
1537
+ * @public
1538
+ * @param storeWrapper
1539
+ * @return {Cache}
1540
+ */
1541
+ /**
1542
+ * Returns the cache instance associated to this Store, instantiates the Cache
1543
+ * if necessary via `Store.createCache`
1544
+ *
1545
+ * @property {Cache} cache
1546
+ * @public
1547
+ */
1548
+ get cache(): Cache;
1549
+ destroy(): void;
1550
+ static create(args?: Record<string, unknown>): Store;
1551
+ }
1552
+ export default Store;
1553
+ }
1554
+ //# sourceMappingURL=store-service.d.ts.map