Documentation / @ember-data/store / index / default
Defined in: packages/store/src/-private/store-service.ts:345
Extends
BaseClass
Properties
identifierCache
identifierCache: IdentifierCache;
Defined in: packages/store/src/-private/store-service.ts:596
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.
lifetimes?
optional lifetimes: CachePolicy;
Defined in: packages/store/src/-private/store-service.ts:654
A Property which an App may set to provide a CachePolicy to control when a cached request becomes stale.
Note, when defined, these methods will only be invoked if a cache key exists for the request, either because the request contains cacheOptions.key
or because the IdentifierCache was able to generate a key for the request using the configured generation method.
isSoftExpired
will only be invoked if isHardExpired
returns false
.
store.lifetimes = {
// make the request and ignore the current cache state
isHardExpired(identifier: StableDocumentIdentifier): boolean {
return false;
}
// make the request in the background if true, return cache state
isSoftExpired(identifier: StableDocumentIdentifier): boolean {
return false;
}
}
notifications
notifications: NotificationManager;
Defined in: packages/store/src/-private/store-service.ts:563
Provides access to the NotificationManager associated with this Store instance.
The NotificationManager can be used to subscribe to changes to the cache.
requestManager
requestManager: default;
Defined in: packages/store/src/-private/store-service.ts:622
Provides access to the requestManager instance associated with this Store instance.
When using ember-data
this property is automatically set to an instance of RequestManager
. When not using ember-data
you must configure this property yourself, either by declaring it as a service or by initializing it.
import Store, { CacheHandler } from '@ember-data/store';
import RequestManager from '@ember-data/request';
import Fetch from '@ember-data/request/fetch';
class extends Store {
requestManager = new RequestManager()
.use([Fetch])
.useCache(CacheHandler);
}
Accessors
cache
Get Signature
get cache(): ReturnType<this["createCache"]>;
Defined in: packages/store/src/-private/store-service.ts:2454
Returns the cache instance associated to this Store, instantiates the Cache if necessary via Store.createCache
Returns
ReturnType
<this
["createCache"
]>
isDestroyed
Set Signature
set isDestroyed(value): void;
Defined in: packages/store/src/-private/store-service.ts:698
Parameters
value
boolean
Returns
void
isDestroying
Set Signature
set isDestroying(value): void;
Defined in: packages/store/src/-private/store-service.ts:691
Parameters
value
boolean
Returns
void
schema
Get Signature
get schema(): ReturnType<this["createSchemaService"]>;
Defined in: packages/store/src/-private/store-service.ts:576
Provides access to the SchemaService instance for this Store instance.
The SchemaService can be used to query for information about the schema of a resource.
Returns
ReturnType
<this
["createSchemaService"
]>
Methods
createCache()
createCache(capabilities): Cache;
Defined in: packages/store/src/-private/store-service.ts:346
Parameters
capabilities
Returns
createRecord()
Call Signature
createRecord<T>(type, inputProperties): T;
Defined in: packages/store/src/-private/store-service.ts:1022
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
:
store.createRecord('post', {
title: 'Ember is awesome!'
});
To create a new instance of a Post
that has a relationship with a User
record:
let user = this.store.peekRecord('user', '1');
store.createRecord('post', {
title: 'Ember is awesome!',
user: user
});
Type Parameters
T
T
Parameters
type
the name of the resource
inputProperties
CreateRecordProperties
<T
>
a hash of properties to set on the newly created record.
Returns
T
record
Call Signature
createRecord(type, inputProperties): unknown;
Defined in: packages/store/src/-private/store-service.ts:1023
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
:
store.createRecord('post', {
title: 'Ember is awesome!'
});
To create a new instance of a Post
that has a relationship with a User
record:
let user = this.store.peekRecord('user', '1');
store.createRecord('post', {
title: 'Ember is awesome!',
user: user
});
Parameters
type
string
the name of the resource
inputProperties
MaybeHasId
& Partial
<FilteredKeys
<MaybeHasId
& Record
<string
, unknown
>>>
a hash of properties to set on the newly created record.
Returns
unknown
record
createSchemaService()
createSchemaService(): SchemaService;
Defined in: packages/store/src/-private/store-service.ts:421
This hook enables an app to supply a SchemaService for use when information about a resource's schema needs to be queried.
This method will only be called once to instantiate the singleton service, which can then be accessed via store.schema
.
For Example, to use the default SchemaService for SchemaRecord
import { SchemaService } from '@warp-drive/schema-record';
class extends Store {
createSchemaService() {
return new SchemaService();
}
}
Or to use the SchemaService for @ember-data/model
import { buildSchema } from '@ember-data/model/hooks';
class extends Store {
createSchemaService() {
return buildSchema(this);
}
}
If you wish to chain services, you must either instantiate each schema source directly or super to retrieve an existing service. For convenience, when migrating from @ember-data/model
to @warp-drive/schema-record
a SchemaService is provided that handles this transition for you:
import { DelegatingSchemaService } from '@ember-data/model/migration-support';
import { SchemaService } from '@warp-drive/schema-record';
class extends Store {
createSchemaService() {
const schema = new SchemaService();
return new DelegatingSchemaService(this, schema);
}
}
When using the DelegateSchemaService, the schema will first be sourced from directly registered schemas, then will fallback to sourcing a schema from available models if no schema is found.
Returns
deleteRecord()
deleteRecord<T>(record): void;
Defined in: packages/store/src/-private/store-service.ts:1101
For symmetry, a record can be deleted via the store.
Example
let post = store.createRecord('post', {
title: 'Ember is awesome!'
});
store.deleteRecord(post);
Type Parameters
T
T
Parameters
record
T
Returns
void
destroy()
destroy(): void;
Defined in: packages/store/src/-private/store-service.ts:2466
Returns
void
findAll()
Call Signature
findAll<T>(type, options?): Promise<IdentifierArray<T>>;
Defined in: packages/store/src/-private/store-service.ts:2075
findAll
asks the adapter's findAll
method to find the records for the given type, and returns a promise which will resolve with all records of this type present in the store, even if the adapter only returns a subset of them.
export default class AuthorsRoute extends Route {
model(params) {
return this.store.findAll('author');
}
}
When the returned promise resolves depends on the reload behavior, configured via the passed options
hash and the result of the adapter's shouldReloadAll
method.
Reloading
If { reload: true }
is passed or adapter.shouldReloadAll
evaluates to true
, then the returned promise resolves once the adapter returns data, regardless if there are already records in the store:
store.push({
data: {
id: 'first',
type: 'author'
}
});
// adapter#findAll resolves with
// [
// {
// id: 'second',
// type: 'author'
// }
// ]
store.findAll('author', { reload: true }).then(function(authors) {
authors.getEach('id'); // ['first', 'second']
});
If no reload is indicated via the above mentioned ways, then the promise immediately resolves with all the records currently loaded in the store.
Background Reloading
Optionally, if adapter.shouldBackgroundReloadAll
evaluates to true
, then a background reload is started. Once this resolves, the array with which the promise resolves, is updated automatically so it contains all the records in the store:
import Adapter from '@ember-data/adapter';
export default class ApplicationAdapter extends Adapter {
shouldReloadAll(store, snapshotsArray) {
return false;
},
shouldBackgroundReloadAll(store, snapshotsArray) {
return true;
}
});
// ...
store.push({
data: {
id: 'first',
type: 'author'
}
});
let allAuthors;
store.findAll('author').then(function(authors) {
authors.getEach('id'); // ['first']
allAuthors = authors;
});
// later, once adapter#findAll resolved with
// [
// {
// id: 'second',
// type: 'author'
// }
// ]
allAuthors.getEach('id'); // ['first', 'second']
If you would like to force or prevent background reloading, you can set a boolean value for backgroundReload
in the options object for findAll
.
export default class PostEditRoute extends Route {
model() {
return this.store.findAll('post', { backgroundReload: false });
}
}
If you pass an object on the adapterOptions
property of the options argument it will be passed to you adapter via the snapshotRecordArray
export default class PostsRoute extends Route {
model(params) {
return this.store.findAll('post', {
adapterOptions: { subscribe: false }
});
}
}
import MyCustomAdapter from './custom-adapter';
export default class UserAdapter extends MyCustomAdapter {
findAll(store, type, sinceToken, snapshotRecordArray) {
if (snapshotRecordArray.adapterOptions.subscribe) {
// ...
}
// ...
}
}
See peekAll to get an array of current records in the store, without waiting until a reload is finished.
Retrieving Related Model Records
If you use an adapter such as Ember's default JSONAPIAdapter
that supports the JSON API specification and if your server endpoint supports the use of an 'include' query parameter, you can use findAll()
to automatically retrieve additional records related to those requested 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 all of the post records we can have the server also return all of the posts' comments in the same request:
export default class PostsRoute extends Route {
model() {
return this.store.findAll('post', { include: ['comments'] });
}
}
Multiple relationships can be requested using an include
parameter consisting of a list or relationship names, while nested relationships can be specified using a dot-separated sequence of relationship names. So to request both the posts' comments and the authors of those comments the request would look like this:
export default class PostsRoute extends Route {
model() {
return this.store.findAll('post', { include: ['comments','comments.author'] });
}
}
See query to only get a subset of records from the server.
Type Parameters
T
T
Parameters
type
the name of the resource
options?
Returns
Promise
<IdentifierArray
<T
>>
promise
Since
1.13.0
Call Signature
findAll(type, options?): Promise<IdentifierArray<unknown>>;
Defined in: packages/store/src/-private/store-service.ts:2076
findAll
asks the adapter's findAll
method to find the records for the given type, and returns a promise which will resolve with all records of this type present in the store, even if the adapter only returns a subset of them.
export default class AuthorsRoute extends Route {
model(params) {
return this.store.findAll('author');
}
}
When the returned promise resolves depends on the reload behavior, configured via the passed options
hash and the result of the adapter's shouldReloadAll
method.
Reloading
If { reload: true }
is passed or adapter.shouldReloadAll
evaluates to true
, then the returned promise resolves once the adapter returns data, regardless if there are already records in the store:
store.push({
data: {
id: 'first',
type: 'author'
}
});
// adapter#findAll resolves with
// [
// {
// id: 'second',
// type: 'author'
// }
// ]
store.findAll('author', { reload: true }).then(function(authors) {
authors.getEach('id'); // ['first', 'second']
});
If no reload is indicated via the above mentioned ways, then the promise immediately resolves with all the records currently loaded in the store.
Background Reloading
Optionally, if adapter.shouldBackgroundReloadAll
evaluates to true
, then a background reload is started. Once this resolves, the array with which the promise resolves, is updated automatically so it contains all the records in the store:
import Adapter from '@ember-data/adapter';
export default class ApplicationAdapter extends Adapter {
shouldReloadAll(store, snapshotsArray) {
return false;
},
shouldBackgroundReloadAll(store, snapshotsArray) {
return true;
}
});
// ...
store.push({
data: {
id: 'first',
type: 'author'
}
});
let allAuthors;
store.findAll('author').then(function(authors) {
authors.getEach('id'); // ['first']
allAuthors = authors;
});
// later, once adapter#findAll resolved with
// [
// {
// id: 'second',
// type: 'author'
// }
// ]
allAuthors.getEach('id'); // ['first', 'second']
If you would like to force or prevent background reloading, you can set a boolean value for backgroundReload
in the options object for findAll
.
export default class PostEditRoute extends Route {
model() {
return this.store.findAll('post', { backgroundReload: false });
}
}
If you pass an object on the adapterOptions
property of the options argument it will be passed to you adapter via the snapshotRecordArray
export default class PostsRoute extends Route {
model(params) {
return this.store.findAll('post', {
adapterOptions: { subscribe: false }
});
}
}
import MyCustomAdapter from './custom-adapter';
export default class UserAdapter extends MyCustomAdapter {
findAll(store, type, sinceToken, snapshotRecordArray) {
if (snapshotRecordArray.adapterOptions.subscribe) {
// ...
}
// ...
}
}
See peekAll to get an array of current records in the store, without waiting until a reload is finished.
Retrieving Related Model Records
If you use an adapter such as Ember's default JSONAPIAdapter
that supports the JSON API specification and if your server endpoint supports the use of an 'include' query parameter, you can use findAll()
to automatically retrieve additional records related to those requested 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 all of the post records we can have the server also return all of the posts' comments in the same request:
export default class PostsRoute extends Route {
model() {
return this.store.findAll('post', { include: ['comments'] });
}
}
Multiple relationships can be requested using an include
parameter consisting of a list or relationship names, while nested relationships can be specified using a dot-separated sequence of relationship names. So to request both the posts' comments and the authors of those comments the request would look like this:
export default class PostsRoute extends Route {
model() {
return this.store.findAll('post', { include: ['comments','comments.author'] });
}
}
See query to only get a subset of records from the server.
Parameters
type
string
the name of the resource
options?
Returns
Promise
<IdentifierArray
<unknown
>>
promise
Since
1.13.0
findRecord()
Call Signature
findRecord<T>(
type,
id,
options?): Promise<T>;
Defined in: packages/store/src/-private/store-service.ts:1494
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
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
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.
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:
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:
export default class Adapter {
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())
}
}
static create() {
return new this();
}
}
This could also be achieved by supplying the post id to the adapter via the adapterOptions property on the options hash.
export default class PostRoute extends Route {
model({ post_id, comment_id: id }) {
return this.store.findRecord({ type: 'comment', id, { adapterOptions: { post: post_id }} });
}
}
export default class Adapter {
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())
}
}
static create() {
return new this();
}
}
If you have access to the post model you can also pass the model itself to preload:
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:
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:
// 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
.
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
export default class PostEditRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, {
adapterOptions: { subscribe: false }
});
}
}
import MyCustomAdapter from './custom-adapter';
export default class PostAdapter extends MyCustomAdapter {
findRecord(store, type, id, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
}
See peekRecord to get the cached version of a record.
Retrieving Related Model Records
If you use an adapter such as Ember's default JSONAPIAdapter
that supports the JSON API specification and if your server endpoint supports the use of an 'include' query parameter, 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:
export default class PostRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { include: ['comments'] });
}
}
export default class Adapter {
findRecord(store, schema, id, snapshot) {
let type = schema.modelName;
if (type === 'post')
let includes = snapshot.adapterOptions.include;
return fetch(`./posts/${postId}?include=${includes}`)
.then(response => response.json())
}
}
static create() {
return new this();
}
}
In this case, the post's comments would then be available in your template as model.comments
.
Multiple relationships can be requested using an include
parameter consisting of a list of relationship names, while nested relationships can be specified using a dot-separated sequence of relationship names. So to request both the post's comments and the authors of those comments the request would look like this:
export default class PostRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { include: ['comments','comments.author'] });
}
}
Retrieving Specific Fields by Type
If your server endpoint supports the use of a 'fields' query parameter, you can use pass those fields through to your server. At this point in time, this requires a few manual steps on your part.
- Implement
buildQuery
in your adapter.
buildQuery(snapshot) {
let query = super.buildQuery(...arguments);
let { fields } = snapshot.adapterOptions;
if (fields) {
query.fields = fields;
}
return query;
}
- Then pass through the applicable fields to your
findRecord
request.
Given a post
model with attributes body, title, publishDate and meta, you can retrieve a filtered list of attributes.
export default class extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title' } });
}
}
Moreover, you can filter attributes on related models as well. If a post
has a belongsTo
relationship to a user, just include the relationship key and attributes.
export default class extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title', user: 'name,email' } });
}
}
Type Parameters
T
T
Parameters
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
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
string
| number
options?
if the first param is a string this will be the optional options for the request. See examples for available options.
Returns
Promise
<T
>
promise
Since
1.13.0
Call Signature
findRecord(
type,
id,
options?): Promise<unknown>;
Defined in: packages/store/src/-private/store-service.ts:1495
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
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
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.
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:
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:
export default class Adapter {
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())
}
}
static create() {
return new this();
}
}
This could also be achieved by supplying the post id to the adapter via the adapterOptions property on the options hash.
export default class PostRoute extends Route {
model({ post_id, comment_id: id }) {
return this.store.findRecord({ type: 'comment', id, { adapterOptions: { post: post_id }} });
}
}
export default class Adapter {
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())
}
}
static create() {
return new this();
}
}
If you have access to the post model you can also pass the model itself to preload:
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:
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:
// 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
.
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
export default class PostEditRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, {
adapterOptions: { subscribe: false }
});
}
}
import MyCustomAdapter from './custom-adapter';
export default class PostAdapter extends MyCustomAdapter {
findRecord(store, type, id, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
}
See peekRecord to get the cached version of a record.
Retrieving Related Model Records
If you use an adapter such as Ember's default JSONAPIAdapter
that supports the JSON API specification and if your server endpoint supports the use of an 'include' query parameter, 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:
export default class PostRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { include: ['comments'] });
}
}
export default class Adapter {
findRecord(store, schema, id, snapshot) {
let type = schema.modelName;
if (type === 'post')
let includes = snapshot.adapterOptions.include;
return fetch(`./posts/${postId}?include=${includes}`)
.then(response => response.json())
}
}
static create() {
return new this();
}
}
In this case, the post's comments would then be available in your template as model.comments
.
Multiple relationships can be requested using an include
parameter consisting of a list of relationship names, while nested relationships can be specified using a dot-separated sequence of relationship names. So to request both the post's comments and the authors of those comments the request would look like this:
export default class PostRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { include: ['comments','comments.author'] });
}
}
Retrieving Specific Fields by Type
If your server endpoint supports the use of a 'fields' query parameter, you can use pass those fields through to your server. At this point in time, this requires a few manual steps on your part.
- Implement
buildQuery
in your adapter.
buildQuery(snapshot) {
let query = super.buildQuery(...arguments);
let { fields } = snapshot.adapterOptions;
if (fields) {
query.fields = fields;
}
return query;
}
- Then pass through the applicable fields to your
findRecord
request.
Given a post
model with attributes body, title, publishDate and meta, you can retrieve a filtered list of attributes.
export default class extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title' } });
}
}
Moreover, you can filter attributes on related models as well. If a post
has a belongsTo
relationship to a user, just include the relationship key and attributes.
export default class extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title', user: 'name,email' } });
}
}
Parameters
type
string
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
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
string
| number
options?
FindRecordOptions
<unknown
>
if the first param is a string this will be the optional options for the request. See examples for available options.
Returns
Promise
<unknown
>
promise
Since
1.13.0
Call Signature
findRecord<T>(resource, options?): Promise<T>;
Defined in: packages/store/src/-private/store-service.ts:1496
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
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
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.
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:
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:
export default class Adapter {
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())
}
}
static create() {
return new this();
}
}
This could also be achieved by supplying the post id to the adapter via the adapterOptions property on the options hash.
export default class PostRoute extends Route {
model({ post_id, comment_id: id }) {
return this.store.findRecord({ type: 'comment', id, { adapterOptions: { post: post_id }} });
}
}
export default class Adapter {
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())
}
}
static create() {
return new this();
}
}
If you have access to the post model you can also pass the model itself to preload:
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:
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:
// 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
.
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
export default class PostEditRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, {
adapterOptions: { subscribe: false }
});
}
}
import MyCustomAdapter from './custom-adapter';
export default class PostAdapter extends MyCustomAdapter {
findRecord(store, type, id, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
}
See peekRecord to get the cached version of a record.
Retrieving Related Model Records
If you use an adapter such as Ember's default JSONAPIAdapter
that supports the JSON API specification and if your server endpoint supports the use of an 'include' query parameter, 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:
export default class PostRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { include: ['comments'] });
}
}
export default class Adapter {
findRecord(store, schema, id, snapshot) {
let type = schema.modelName;
if (type === 'post')
let includes = snapshot.adapterOptions.include;
return fetch(`./posts/${postId}?include=${includes}`)
.then(response => response.json())
}
}
static create() {
return new this();
}
}
In this case, the post's comments would then be available in your template as model.comments
.
Multiple relationships can be requested using an include
parameter consisting of a list of relationship names, while nested relationships can be specified using a dot-separated sequence of relationship names. So to request both the post's comments and the authors of those comments the request would look like this:
export default class PostRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { include: ['comments','comments.author'] });
}
}
Retrieving Specific Fields by Type
If your server endpoint supports the use of a 'fields' query parameter, you can use pass those fields through to your server. At this point in time, this requires a few manual steps on your part.
- Implement
buildQuery
in your adapter.
buildQuery(snapshot) {
let query = super.buildQuery(...arguments);
let { fields } = snapshot.adapterOptions;
if (fields) {
query.fields = fields;
}
return query;
}
- Then pass through the applicable fields to your
findRecord
request.
Given a post
model with attributes body, title, publishDate and meta, you can retrieve a filtered list of attributes.
export default class extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title' } });
}
}
Moreover, you can filter attributes on related models as well. If a post
has a belongsTo
relationship to a user, just include the relationship key and attributes.
export default class extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title', user: 'name,email' } });
}
}
Type Parameters
T
T
Parameters
resource
ResourceIdentifierObject
<TypeFromInstance
<T
>>
options?
if the first param is a string this will be the optional options for the request. See examples for available options.
Returns
Promise
<T
>
promise
Since
1.13.0
Call Signature
findRecord(resource, options?): Promise<unknown>;
Defined in: packages/store/src/-private/store-service.ts:1497
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
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
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.
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:
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:
export default class Adapter {
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())
}
}
static create() {
return new this();
}
}
This could also be achieved by supplying the post id to the adapter via the adapterOptions property on the options hash.
export default class PostRoute extends Route {
model({ post_id, comment_id: id }) {
return this.store.findRecord({ type: 'comment', id, { adapterOptions: { post: post_id }} });
}
}
export default class Adapter {
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())
}
}
static create() {
return new this();
}
}
If you have access to the post model you can also pass the model itself to preload:
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:
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:
// 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
.
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
export default class PostEditRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, {
adapterOptions: { subscribe: false }
});
}
}
import MyCustomAdapter from './custom-adapter';
export default class PostAdapter extends MyCustomAdapter {
findRecord(store, type, id, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
}
See peekRecord to get the cached version of a record.
Retrieving Related Model Records
If you use an adapter such as Ember's default JSONAPIAdapter
that supports the JSON API specification and if your server endpoint supports the use of an 'include' query parameter, 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:
export default class PostRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { include: ['comments'] });
}
}
export default class Adapter {
findRecord(store, schema, id, snapshot) {
let type = schema.modelName;
if (type === 'post')
let includes = snapshot.adapterOptions.include;
return fetch(`./posts/${postId}?include=${includes}`)
.then(response => response.json())
}
}
static create() {
return new this();
}
}
In this case, the post's comments would then be available in your template as model.comments
.
Multiple relationships can be requested using an include
parameter consisting of a list of relationship names, while nested relationships can be specified using a dot-separated sequence of relationship names. So to request both the post's comments and the authors of those comments the request would look like this:
export default class PostRoute extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { include: ['comments','comments.author'] });
}
}
Retrieving Specific Fields by Type
If your server endpoint supports the use of a 'fields' query parameter, you can use pass those fields through to your server. At this point in time, this requires a few manual steps on your part.
- Implement
buildQuery
in your adapter.
buildQuery(snapshot) {
let query = super.buildQuery(...arguments);
let { fields } = snapshot.adapterOptions;
if (fields) {
query.fields = fields;
}
return query;
}
- Then pass through the applicable fields to your
findRecord
request.
Given a post
model with attributes body, title, publishDate and meta, you can retrieve a filtered list of attributes.
export default class extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title' } });
}
}
Moreover, you can filter attributes on related models as well. If a post
has a belongsTo
relationship to a user, just include the relationship key and attributes.
export default class extends Route {
model(params) {
return this.store.findRecord('post', params.post_id, { adapterOptions: { fields: { post: 'body,title', user: 'name,email' } });
}
}
Parameters
resource
options?
FindRecordOptions
<unknown
>
if the first param is a string this will be the optional options for the request. See examples for available options.
Returns
Promise
<unknown
>
promise
Since
1.13.0
getReference()
getReference(resource, id): RecordReference;
Defined in: packages/store/src/-private/store-service.ts:1590
Get the reference for the specified record.
Example
let userRef = store.getReference('user', '1');
// check if the user is loaded
let isLoaded = userRef.value() !== null;
// get the record of the reference (null if not yet available)
let user = userRef.value();
// get the identifier of the reference
if (userRef.remoteType() === 'id') {
let id = userRef.id();
}
// load user (via store.find)
userRef.load().then(...)
// or trigger a reload
userRef.reload().then(...)
// provide data for reference
userRef.push({ id: 1, username: '@user' }).then(function(user) {
userRef.value() === user;
});
Parameters
resource
modelName (string) or Identifier (object)
string
| ResourceIdentifierObject
id
string
| number
Returns
RecordReference
Since
2.5.0
getRequestStateService()
getRequestStateService(): RequestStateService;
Defined in: packages/store/src/-private/store-service.ts:793
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.
Returns
RequestStateService
getSchemaDefinitionService()
getSchemaDefinitionService(): SchemaService;
Defined in: packages/store/src/-private/store-service.ts:435
DEPRECATED - Use the property store.schema
instead.
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.
Returns
Deprecated
instantiateRecord()
instantiateRecord<T>(identifier, createRecordArgs): unknown;
Defined in: packages/store/src/-private/store-service.ts:353
This is the hook WarpDrive uses to create a record instance to give reactive access to a resource in the cache.
Type Parameters
T
T
Parameters
identifier
createRecordArgs
Returns
unknown
modelFor()
Call Signature
modelFor<T>(type): ModelSchema<T>;
Defined in: packages/store/src/-private/store-service.ts:980
Returns the schema for a particular resource type (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
for example.
Type Parameters
T
T
Parameters
type
Returns
ModelSchema
<T
>
Deprecated
Call Signature
modelFor(type): ModelSchema;
Defined in: packages/store/src/-private/store-service.ts:981
Returns the schema for a particular resource type (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
for example.
Parameters
type
string
Returns
Deprecated
peekAll()
Call Signature
peekAll<T>(type): IdentifierArray<T>;
Defined in: packages/store/src/-private/store-service.ts:2123
This method returns a filtered array that contains all of the known records for a given type in the store.
Note that because it's just a filter, the result will contain any locally created records of the type, however, it will not make a request to the backend to retrieve additional records. If you would like to request all the records from the backend please use store.findAll.
Also note that multiple calls to peekAll
for a given type will always return the same RecordArray
.
Example
let localPosts = store.peekAll('post');
Type Parameters
T
T
Parameters
type
the name of the resource
Returns
IdentifierArray
<T
>
Since
1.13.0
Call Signature
peekAll(type): IdentifierArray;
Defined in: packages/store/src/-private/store-service.ts:2124
This method returns a filtered array that contains all of the known records for a given type in the store.
Note that because it's just a filter, the result will contain any locally created records of the type, however, it will not make a request to the backend to retrieve additional records. If you would like to request all the records from the backend please use store.findAll.
Also note that multiple calls to peekAll
for a given type will always return the same RecordArray
.
Example
let localPosts = store.peekAll('post');
Parameters
type
string
the name of the resource
Returns
IdentifierArray
Since
1.13.0
peekRecord()
Call Signature
peekRecord<T>(type, id): null | T;
Defined in: packages/store/src/-private/store-service.ts:1661
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it is available in the store, otherwise it will return null
. A record is available if it has been fetched earlier, or pushed manually into the store.
See findRecord if you would like to request this record from the backend.
Note: This is a synchronous method and does not return a promise.
Example 1
let post = store.peekRecord('post', '1');
post.id; // '1'
peekRecord
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
Example 2
let post = store.peekRecord({ type: 'post', id });
post.id; // '1'
If you have previously received an lid from an Identifier for this record, you can lookup the record again using just the lid.
Example 3
let post = store.peekRecord({ lid });
post.id; // '1'
Type Parameters
T
T
Parameters
type
id
optional only if the first param is a ResourceIdentifier, else the string id of the record to be retrieved.
string
| number
Returns
null
| T
record
Since
1.13.0
Call Signature
peekRecord(type, id): unknown;
Defined in: packages/store/src/-private/store-service.ts:1662
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it is available in the store, otherwise it will return null
. A record is available if it has been fetched earlier, or pushed manually into the store.
See findRecord if you would like to request this record from the backend.
Note: This is a synchronous method and does not return a promise.
Example 1
let post = store.peekRecord('post', '1');
post.id; // '1'
peekRecord
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
Example 2
let post = store.peekRecord({ type: 'post', id });
post.id; // '1'
If you have previously received an lid from an Identifier for this record, you can lookup the record again using just the lid.
Example 3
let post = store.peekRecord({ lid });
post.id; // '1'
Parameters
type
string
id
optional only if the first param is a ResourceIdentifier, else the string id of the record to be retrieved.
string
| number
Returns
unknown
record
Since
1.13.0
Call Signature
peekRecord<T>(identifier): null | T;
Defined in: packages/store/src/-private/store-service.ts:1663
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it is available in the store, otherwise it will return null
. A record is available if it has been fetched earlier, or pushed manually into the store.
See findRecord if you would like to request this record from the backend.
Note: This is a synchronous method and does not return a promise.
Example 1
let post = store.peekRecord('post', '1');
post.id; // '1'
peekRecord
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
Example 2
let post = store.peekRecord({ type: 'post', id });
post.id; // '1'
If you have previously received an lid from an Identifier for this record, you can lookup the record again using just the lid.
Example 3
let post = store.peekRecord({ lid });
post.id; // '1'
Type Parameters
T
T
Parameters
identifier
ResourceIdentifierObject
<TypeFromInstance
<T
>>
Returns
null
| T
record
Since
1.13.0
Call Signature
peekRecord(identifier): unknown;
Defined in: packages/store/src/-private/store-service.ts:1664
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it is available in the store, otherwise it will return null
. A record is available if it has been fetched earlier, or pushed manually into the store.
See findRecord if you would like to request this record from the backend.
Note: This is a synchronous method and does not return a promise.
Example 1
let post = store.peekRecord('post', '1');
post.id; // '1'
peekRecord
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
Example 2
let post = store.peekRecord({ type: 'post', id });
post.id; // '1'
If you have previously received an lid from an Identifier for this record, you can lookup the record again using just the lid.
Example 3
let post = store.peekRecord({ lid });
post.id; // '1'
Parameters
identifier
Returns
unknown
record
Since
1.13.0
push()
Call Signature
push(data): null;
Defined in: packages/store/src/-private/store-service.ts:2328
Push some data for a given type into the store.
This method expects normalized JSON API document. This means you have to follow JSON API specification with few minor adjustments:
- record's
type
should always be in singular, dasherized form - members (properties) should be camelCased
Your primary data should be wrapped inside data
property:
store.push({
data: {
// primary data for single record of type `Person`
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
}
});
data
property can also hold an array (of records):
store.push({
data: [
// an array of records
{
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
},
{
id: '2',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
}
}
]
});
There are some typical properties for JSONAPI
payload:
id
- mandatory, unique record's keytype
- mandatory string which matchesmodel
's dasherized name in singular formattributes
- object which holds data for record attributes -attr
's declared in modelrelationships
- object which must contain any of the following properties under each relationships' respective key (example path isrelationships.achievements.data
):
For this model:
import Model, { attr, hasMany } from '@ember-data/model';
export default class PersonRoute extends Route {
@attr('string') firstName;
@attr('string') lastName;
@hasMany('person') children;
}
To represent the children as IDs:
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
data: [
{
id: '2',
type: 'person'
},
{
id: '3',
type: 'person'
},
{
id: '4',
type: 'person'
}
]
}
}
}
}
To represent the children relationship as a URL:
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
links: {
related: '/people/1/children'
}
}
}
}
}
If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's normalize method is a convenience helper for converting a json payload into the form Ember Data expects.
store.push(store.normalize('person', data));
This method can be used both to push in brand new records, as well as to update existing records.
Parameters
data
Returns
null
the record(s) that was created or updated.
Call Signature
push<T>(data): T;
Defined in: packages/store/src/-private/store-service.ts:2329
Push some data for a given type into the store.
This method expects normalized JSON API document. This means you have to follow JSON API specification with few minor adjustments:
- record's
type
should always be in singular, dasherized form - members (properties) should be camelCased
Your primary data should be wrapped inside data
property:
store.push({
data: {
// primary data for single record of type `Person`
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
}
});
data
property can also hold an array (of records):
store.push({
data: [
// an array of records
{
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
},
{
id: '2',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
}
}
]
});
There are some typical properties for JSONAPI
payload:
id
- mandatory, unique record's keytype
- mandatory string which matchesmodel
's dasherized name in singular formattributes
- object which holds data for record attributes -attr
's declared in modelrelationships
- object which must contain any of the following properties under each relationships' respective key (example path isrelationships.achievements.data
):
For this model:
import Model, { attr, hasMany } from '@ember-data/model';
export default class PersonRoute extends Route {
@attr('string') firstName;
@attr('string') lastName;
@hasMany('person') children;
}
To represent the children as IDs:
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
data: [
{
id: '2',
type: 'person'
},
{
id: '3',
type: 'person'
},
{
id: '4',
type: 'person'
}
]
}
}
}
}
To represent the children relationship as a URL:
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
links: {
related: '/people/1/children'
}
}
}
}
}
If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's normalize method is a convenience helper for converting a json payload into the form Ember Data expects.
store.push(store.normalize('person', data));
This method can be used both to push in brand new records, as well as to update existing records.
Type Parameters
T
T
Parameters
data
SingleResourceDocument
<TypeFromInstance
<T
>>
Returns
T
the record(s) that was created or updated.
Call Signature
push(data): unknown;
Defined in: packages/store/src/-private/store-service.ts:2330
Push some data for a given type into the store.
This method expects normalized JSON API document. This means you have to follow JSON API specification with few minor adjustments:
- record's
type
should always be in singular, dasherized form - members (properties) should be camelCased
Your primary data should be wrapped inside data
property:
store.push({
data: {
// primary data for single record of type `Person`
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
}
});
data
property can also hold an array (of records):
store.push({
data: [
// an array of records
{
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
},
{
id: '2',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
}
}
]
});
There are some typical properties for JSONAPI
payload:
id
- mandatory, unique record's keytype
- mandatory string which matchesmodel
's dasherized name in singular formattributes
- object which holds data for record attributes -attr
's declared in modelrelationships
- object which must contain any of the following properties under each relationships' respective key (example path isrelationships.achievements.data
):
For this model:
import Model, { attr, hasMany } from '@ember-data/model';
export default class PersonRoute extends Route {
@attr('string') firstName;
@attr('string') lastName;
@hasMany('person') children;
}
To represent the children as IDs:
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
data: [
{
id: '2',
type: 'person'
},
{
id: '3',
type: 'person'
},
{
id: '4',
type: 'person'
}
]
}
}
}
}
To represent the children relationship as a URL:
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
links: {
related: '/people/1/children'
}
}
}
}
}
If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's normalize method is a convenience helper for converting a json payload into the form Ember Data expects.
store.push(store.normalize('person', data));
This method can be used both to push in brand new records, as well as to update existing records.
Parameters
data
Returns
unknown
the record(s) that was created or updated.
Call Signature
push<T>(data): T[];
Defined in: packages/store/src/-private/store-service.ts:2331
Push some data for a given type into the store.
This method expects normalized JSON API document. This means you have to follow JSON API specification with few minor adjustments:
- record's
type
should always be in singular, dasherized form - members (properties) should be camelCased
Your primary data should be wrapped inside data
property:
store.push({
data: {
// primary data for single record of type `Person`
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
}
});
data
property can also hold an array (of records):
store.push({
data: [
// an array of records
{
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
},
{
id: '2',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
}
}
]
});
There are some typical properties for JSONAPI
payload:
id
- mandatory, unique record's keytype
- mandatory string which matchesmodel
's dasherized name in singular formattributes
- object which holds data for record attributes -attr
's declared in modelrelationships
- object which must contain any of the following properties under each relationships' respective key (example path isrelationships.achievements.data
):
For this model:
import Model, { attr, hasMany } from '@ember-data/model';
export default class PersonRoute extends Route {
@attr('string') firstName;
@attr('string') lastName;
@hasMany('person') children;
}
To represent the children as IDs:
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
data: [
{
id: '2',
type: 'person'
},
{
id: '3',
type: 'person'
},
{
id: '4',
type: 'person'
}
]
}
}
}
}
To represent the children relationship as a URL:
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
links: {
related: '/people/1/children'
}
}
}
}
}
If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's normalize method is a convenience helper for converting a json payload into the form Ember Data expects.
store.push(store.normalize('person', data));
This method can be used both to push in brand new records, as well as to update existing records.
Type Parameters
T
T
Parameters
data
CollectionResourceDocument
<TypeFromInstance
<T
>>
Returns
T
[]
the record(s) that was created or updated.
Call Signature
push(data): unknown[];
Defined in: packages/store/src/-private/store-service.ts:2332
Push some data for a given type into the store.
This method expects normalized JSON API document. This means you have to follow JSON API specification with few minor adjustments:
- record's
type
should always be in singular, dasherized form - members (properties) should be camelCased
Your primary data should be wrapped inside data
property:
store.push({
data: {
// primary data for single record of type `Person`
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
}
});
data
property can also hold an array (of records):
store.push({
data: [
// an array of records
{
id: '1',
type: 'person',
attributes: {
firstName: 'Daniel',
lastName: 'Kmak'
}
},
{
id: '2',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
}
}
]
});
There are some typical properties for JSONAPI
payload:
id
- mandatory, unique record's keytype
- mandatory string which matchesmodel
's dasherized name in singular formattributes
- object which holds data for record attributes -attr
's declared in modelrelationships
- object which must contain any of the following properties under each relationships' respective key (example path isrelationships.achievements.data
):
For this model:
import Model, { attr, hasMany } from '@ember-data/model';
export default class PersonRoute extends Route {
@attr('string') firstName;
@attr('string') lastName;
@hasMany('person') children;
}
To represent the children as IDs:
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
data: [
{
id: '2',
type: 'person'
},
{
id: '3',
type: 'person'
},
{
id: '4',
type: 'person'
}
]
}
}
}
}
To represent the children relationship as a URL:
{
data: {
id: '1',
type: 'person',
attributes: {
firstName: 'Tom',
lastName: 'Dale'
},
relationships: {
children: {
links: {
related: '/people/1/children'
}
}
}
}
}
If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's normalize method is a convenience helper for converting a json payload into the form Ember Data expects.
store.push(store.normalize('person', data));
This method can be used both to push in brand new records, as well as to update existing records.
Parameters
data
Returns
unknown
[]
the record(s) that was created or updated.
query()
Call Signature
query<T>(
type,
query,
options?): Promise<Collection<T>>;
Defined in: packages/store/src/-private/store-service.ts:1745
This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application.
Each time this method is called a new request is made through the adapter.
Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them.
If you do something like this:
store.query('person', { page: 1 });
The request made to the server will look something like this:
GET "/api/v1/person?page=1"
If you do something like this:
store.query('person', { ids: ['1', '2', '3'] });
The request made to the server will look something like this:
GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3"
decoded: "/api/v1/person?ids[]=1&ids[]=2&ids[]=3"
This method returns a promise, which is resolved with a Collection
once the server returns.
Type Parameters
T
T
Parameters
type
the name of the resource
query
a query to be used by the adapter
options?
optional, may include adapterOptions
hash which will be passed to adapter.query
Returns
Promise
<Collection
<T
>>
promise
Since
1.13.0
Call Signature
query(
type,
query,
options?): Promise<Collection<unknown>>;
Defined in: packages/store/src/-private/store-service.ts:1746
This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application.
Each time this method is called a new request is made through the adapter.
Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them.
If you do something like this:
store.query('person', { page: 1 });
The request made to the server will look something like this:
GET "/api/v1/person?page=1"
If you do something like this:
store.query('person', { ids: ['1', '2', '3'] });
The request made to the server will look something like this:
GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3"
decoded: "/api/v1/person?ids[]=1&ids[]=2&ids[]=3"
This method returns a promise, which is resolved with a Collection
once the server returns.
Parameters
type
string
the name of the resource
query
a query to be used by the adapter
options?
optional, may include adapterOptions
hash which will be passed to adapter.query
Returns
Promise
<Collection
<unknown
>>
promise
Since
1.13.0
queryRecord()
Call Signature
queryRecord<T>(
type,
query,
options?): Promise<null | T>;
Defined in: packages/store/src/-private/store-service.ts:1868
This method makes a request for one record, where the id
is not known beforehand (if the id
is known, use findRecord
instead).
This method can be used when it is certain that the server will return a single object for the primary data.
Each time this method is called a new request is made through the adapter.
Let's assume our API provides an endpoint for the currently logged in user via:
// GET /api/current_user
{
user: {
id: 1234,
username: 'admin'
}
}
Since the specific id
of the user
is not known beforehand, we can use queryRecord
to get the user:
store.queryRecord('user', {}).then(function(user) {
let username = user.username;
// do thing
});
The request is made through the adapters' queryRecord
:
import Adapter from '@ember-data/adapter';
import $ from 'jquery';
export default class UserAdapter extends Adapter {
queryRecord(modelName, query) {
return $.getJSON('/api/current_user');
}
}
Note: the primary use case for store.queryRecord
is when a single record is queried and the id
is not known beforehand. In all other cases store.query
and using the first item of the array is likely the preferred way:
// GET /users?username=unique
{
data: [{
id: 1234,
type: 'user',
attributes: {
username: "unique"
}
}]
}
store.query('user', { username: 'unique' }).then(function(users) {
return users.firstObject;
}).then(function(user) {
let id = user.id;
});
This method returns a promise, which resolves with the found record.
If the adapter returns no data for the primary data of the payload, then queryRecord
resolves with null
:
// GET /users?username=unique
{
data: null
}
store.queryRecord('user', { username: 'unique' }).then(function(user) {
// user is null
});
Type Parameters
T
T
Parameters
type
query
an opaque query to be used by the adapter
options?
optional, may include adapterOptions
hash which will be passed to adapter.queryRecord
Returns
Promise
<null
| T
>
promise which resolves with the found record or null
Since
1.13.0
Call Signature
queryRecord(
type,
query,
options?): Promise<unknown>;
Defined in: packages/store/src/-private/store-service.ts:1869
This method makes a request for one record, where the id
is not known beforehand (if the id
is known, use findRecord
instead).
This method can be used when it is certain that the server will return a single object for the primary data.
Each time this method is called a new request is made through the adapter.
Let's assume our API provides an endpoint for the currently logged in user via:
// GET /api/current_user
{
user: {
id: 1234,
username: 'admin'
}
}
Since the specific id
of the user
is not known beforehand, we can use queryRecord
to get the user:
store.queryRecord('user', {}).then(function(user) {
let username = user.username;
// do thing
});
The request is made through the adapters' queryRecord
:
import Adapter from '@ember-data/adapter';
import $ from 'jquery';
export default class UserAdapter extends Adapter {
queryRecord(modelName, query) {
return $.getJSON('/api/current_user');
}
}
Note: the primary use case for store.queryRecord
is when a single record is queried and the id
is not known beforehand. In all other cases store.query
and using the first item of the array is likely the preferred way:
// GET /users?username=unique
{
data: [{
id: 1234,
type: 'user',
attributes: {
username: "unique"
}
}]
}
store.query('user', { username: 'unique' }).then(function(users) {
return users.firstObject;
}).then(function(user) {
let id = user.id;
});
This method returns a promise, which resolves with the found record.
If the adapter returns no data for the primary data of the payload, then queryRecord
resolves with null
:
// GET /users?username=unique
{
data: null
}
store.queryRecord('user', { username: 'unique' }).then(function(user) {
// user is null
});
Parameters
type
string
query
an opaque query to be used by the adapter
options?
optional, may include adapterOptions
hash which will be passed to adapter.queryRecord
Returns
Promise
<unknown
>
promise which resolves with the found record or null
Since
1.13.0
registerSchema()
registerSchema(schema): void;
Defined in: packages/store/src/-private/store-service.ts:545
DEPRECATED - Use createSchemaService
instead.
Allows an app to register a custom SchemaService for use when information about a resource's schema needs to be queried.
This method can only be called more than once, but only one schema definition service may exist. Therefore if you wish to chain services you must lookup the existing service and close over it with the new service by accessing store.schema
prior to registration.
For Example:
import Store from '@ember-data/store';
class SchemaDelegator {
constructor(schema) {
this._schema = schema;
}
hasResource(resource: { type: string }): boolean {
if (AbstractSchemas.has(resource.type)) {
return true;
}
return this._schema.hasResource(resource);
}
attributesDefinitionFor(identifier: RecordIdentifier | { type: string }): AttributesSchema {
return this._schema.attributesDefinitionFor(identifier);
}
relationshipsDefinitionFor(identifier: RecordIdentifier | { type: string }): RelationshipsSchema {
const schema = AbstractSchemas.get(identifier.type);
return schema || this._schema.relationshipsDefinitionFor(identifier);
}
}
export default class extends Store {
constructor(...args) {
super(...args);
const schema = this.schema;
this.registerSchema(new SchemaDelegator(schema));
}
}
Parameters
schema
Returns
void
Deprecated
registerSchemaDefinitionService()
registerSchemaDefinitionService(schema): void;
Defined in: packages/store/src/-private/store-service.ts:490
DEPRECATED - Use createSchemaService
instead.
Allows an app to register a custom SchemaService for use when information about a resource's schema needs to be queried.
This method can only be called more than once, but only one schema definition service may exist. Therefore if you wish to chain services you must lookup the existing service and close over it with the new service by accessing store.schema
prior to registration.
For Example:
import Store from '@ember-data/store';
class SchemaDelegator {
constructor(schema) {
this._schema = schema;
}
hasResource(resource: { type: string }): boolean {
if (AbstractSchemas.has(resource.type)) {
return true;
}
return this._schema.hasResource(resource);
}
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.createSchemaService();
this.registerSchemaDefinitionService(new SchemaDelegator(schema));
}
}
Parameters
schema
Returns
void
Deprecated
request()
request<RT, T>(requestConfig): Future<RT>;
Defined in: packages/store/src/-private/store-service.ts:867
Issue a request via the configured RequestManager, inserting the response into the cache and handing back a Future which resolves to a ResponseDocument
Cache Keys
Only GET requests with a url or requests with an explicit cache key (cacheOptions.key
) will have the request result and document cached.
The cache key used is requestConfig.cacheOptions.key
if present, falling back to requestConfig.url
.
Params are not serialized as part of the cache-key, so either ensure they are already in the url or utilize requestConfig.cacheOptions.key
. For queries issued via the POST
method requestConfig.cacheOptions.key
MUST be supplied for the document to be cached.
Requesting Without a Cache Key
Resource data within the request is always updated in the cache, regardless of whether a cache key is present for the request.
Fulfilling From Cache
When a cache-key is determined, the request may fulfill from cache provided the cache is not stale.
Cache staleness is determined by the configured CachePolicy with priority given to the cacheOptions.reload
and cacheOptions.backgroundReload
on the request if present.
If the cache data has soft expired or the request asks for a background reload, the request will fulfill from cache if possible and make a non-blocking request in the background to update the cache.
If the cache data has hard expired or the request asks for a reload, the request will not fulfill from cache and will make a blocking request to update the cache.
The Response
The primary difference between requestManager.request
and store.request
is that store.request
will attempt to hydrate the response content into a response Document containing RecordInstances.
Type Parameters
RT
RT
T
T
= unknown
Parameters
requestConfig
StoreRequestInput
<RT
, T
>
Returns
Future
<RT
>
saveRecord()
saveRecord<T>(record, options): Promise<T>;
Defined in: packages/store/src/-private/store-service.ts:2389
Trigger a save for a Record.
Returns a promise resolving with the same record when the save is complete.
Type Parameters
T
T
Parameters
record
T
options
Record
<string
, unknown
> = {}
Returns
Promise
<T
>
teardownRecord()
teardownRecord(record): void;
Defined in: packages/store/src/-private/store-service.ts:361
This is the hook WarpDrive uses to remove a record instance that is no longer needed
Parameters
record
unknown
Returns
void
unloadAll()
Call Signature
unloadAll<T>(type): void;
Defined in: packages/store/src/-private/store-service.ts:2152
This method unloads all records in the store. It schedules unloading to happen during the next run loop.
Optionally you can pass a type which unload all records for a given type.
store.unloadAll();
store.unloadAll('post');
Type Parameters
T
T
Parameters
type
the name of the resource
Returns
void
Call Signature
unloadAll(type?): void;
Defined in: packages/store/src/-private/store-service.ts:2153
This method unloads all records in the store. It schedules unloading to happen during the next run loop.
Optionally you can pass a type which unload all records for a given type.
store.unloadAll();
store.unloadAll('post');
Parameters
type?
string
the name of the resource
Returns
void
unloadRecord()
unloadRecord<T>(record): void;
Defined in: packages/store/src/-private/store-service.ts:1132
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
const { content: { data: post } } = await store.request(findRecord({ type: 'post', id: '1' }));
store.unloadRecord(post);
Type Parameters
T
T
Parameters
record
T
Returns
void
create()
static create(args?): Store;
Defined in: packages/store/src/-private/store-service.ts:2484
Parameters
args?
Record
<string
, unknown
>
Returns
Store