DS.Store Class packages/ember-data/lib/system/store.js:44
The store contains all of the data for records loaded from the server. It is also responsible for creating instances of DS.Model that wrap the individual data for a record, so that they can be bound to in your Handlebars templates.
Define your application's store like this:
1 |
MyApp.Store = DS.Store.extend(); |
Most Ember.js applications will only have a single DS.Store
that is
automatically created by their Ember.Application
.
You can retrieve models from the store in several ways. To retrieve a record
for a specific id, use DS.Model
's find()
method:
1 |
var person = App.Person.find(123); |
If your application has multiple DS.Store
instances (an unusual case), you can
specify which store should be used:
1 |
var person = store.find(App.Person, 123); |
In general, you should retrieve models using the methods on DS.Model
; you should
rarely need to interact with the store directly.
By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter:
1 2 3 |
MyApp.store = DS.Store.create({ adapter: 'MyApp.CustomAdapter' }); |
You can learn more about writing a custom adapter by reading the DS.Adapter
documentation.
Methods
- _load
- adapterFor
- all
- buildRecord
- createRecord
- dataWasUpdated
- deleteRecord
- dematerializeRecord
- didSaveRecord
- didUpdateAll
- fetchAll
- fetchMany
- fetchRecord
- filter
- find
- findAll
- findById
- findByIds
- findHasMany
- findMany
- findQuery
- flushPendingSave
- generateId
- getById
- hasRecordForId
- init
- metaForType
- metadataFor
- modelFor
- push
- pushMany
- pushPayload
- recordForId
- recordIsLoaded
- recordWasError
- recordWasInvalid
- reloadRecord
- scheduleSave
- serialize
- serializerFor
- typeMapFor
- unloadAll
- unloadRecord
- updateId
Properties
_load
(type, data, partial)
private
This internal method is used by push
.
Parameters:
- type DS.Model
- data Object
- partial Boolean
- the data should be merged into the existing data, not replace it.
adapterFor
(type)
private
Returns the adapter for a given type.
Parameters:
- type subclass of DS.Model
Returns:
- DS.Adapter
all
(type)
DS.RecordArray
This method returns a filtered array that contains all of the known records for a given type.
Note that because it's just a filter, it will have any locally created records of the type.
Also note that multiple calls to all
for a given type will always
return the same RecordArray.
Parameters:
- type Class
Returns:
buildRecord
(type, id, data)
private
Build a brand new record for a given type, ID, and initial data.
Parameters:
- type subclass of DS.Model
- id String
- data Object
Returns:
- DS.Model
createRecord
(type, properties)
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 App.Post
:
1 2 3 |
store.createRecord('post', { title: "Rails is omakase" }); |
Parameters:
- type String
- properties Object
- a hash of properties to set on the newly created record.
Returns:
- DS.Model
dataWasUpdated
(type, clientId, record)
private
If the adapter updates attributes or acknowledges creation or deletion, the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per
run loop per record.
Parameters:
- type Class
- clientId Number|String
- record DS.Model
deleteRecord
(record)
For symmetry, a record can be deleted via the store.
Parameters:
- record DS.Model
dematerializeRecord
(record)
private
When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed.
Parameters:
- record DS.Model
didSaveRecord
(record, data)
private
This method is called once the promise returned by an
adapter's createRecord
, updateRecord
or deleteRecord
is resolved.
If the data provides a server-generated ID, it will update the record and the store's indexes.
Parameters:
- record DS.Model
- the in-flight record
- data Object
- optional data (see above)
didUpdateAll
(type)
Parameters:
- type
fetchAll
(type, array)
private
Parameters:
- type
- array
Returns:
- Promise
fetchMany
(records, owner)
private
This method takes a list of records, groups the records by type,
converts the records into IDs, and then invokes the adapter's findMany
method.
The records are grouped by type to invoke findMany
on adapters
for each unique type in records.
It is used both by a brand new relationship (via the findMany
method) or when the data underlying an existing relationship
changes.
Parameters:
- records
- owner
fetchRecord
(record)
private
This method is called by findById
if it discovers that a particular
type/id pair hasn't been loaded yet to kick off a request to the
adapter.
Parameters:
- record DS.Model
Returns:
- Promise
filter
(type, query, filter)
DS.FilteredRecordArray
Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally.
The callback function takes a materialized record, and returns true if the record should be included in the filter and false if it should not.
The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record.
If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array.
Optionally you can pass a query which will be triggered at first. The results returned by the server could then appear in the filter if they match the filter function.
Parameters:
- type Class
- query Object
- optional query
- filter Function
Returns:
find
(type, id)
This is the main entry point into finding records. The first parameter to this method is the model's name as a string.
To find a record by ID, pass the id
as the second parameter:
1 |
store.find('person', 1); |
The find
method will always return a promise that will be resolved
with the record. If the record was already in the store, the promise will
be resolved immediately. Otherwise, the store will ask the adapter's find
method to find the necessary data.
The find
method will always resolve its promise with the same object for
a given type and id
.
To find all records for a type, call find
with no additional parameters:
1 |
store.find('person');
|
This will ask the adapter's findAll
method to find the records for the
given type, and return a promise that will be resolved once the server
returns the values.
To find a record by a query, call find
with a hash as the second
parameter:
1 |
store.find(App.Person, { page: 1 }); |
This will ask the adapter's findQuery
method to find the records for
the query, and return a promise that will be resolved once the server
responds.
Parameters:
- type DS.Model
- id Object|String|Integer|null
findAll
(type)
DS.AdapterPopulatedRecordArray
private
This method returns an array of all records adapter can find.
It triggers the adapter's findAll
method to give it an opportunity to populate
the array with records of that type.
Parameters:
- type Class
Returns:
findById
(type, id)
private
This method returns a record for a given type and id combination.
Parameters:
- type
- id
findByIds
(type, ids)
private
This method makes a series of requests to the adapter's find
method
and returns a promise that resolves once they are all loaded.
Parameters:
- type String
- ids Array
Returns:
- Promise
findHasMany
(owner, link, type, resolver)
private
If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched.
The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants.
The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship.
Returns:
- DS.ManyArray
findMany
(owner, records, type, resolver)
private
Returns:
- DS.ManyArray
findQuery
(type, query)
private
This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application.
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.
This method returns a promise, which is resolved with a RecordArray
once the server returns.
Parameters:
- type String
- query Any
- an opaque query to be used by the adapter
Returns:
- Promise
flushPendingSave
private
This method is called at the end of the run loop, and
flushes any records passed into scheduleSave
generateId
(type)
If possible, this method asks the adapter to generate an ID for a newly created record.
Parameters:
- type String
Returns:
- String if the adapter can generate one, an ID
getById
(type, id)
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it's available. Otherwise, it will return null.
1 |
var post = store.getById('post', 1); |
Parameters:
- type
- id
hasRecordForId
(type, id)
Returns true if a record for a given type and ID is already loaded.
Parameters:
- type DS.Model
- id String|Integer
Returns:
- Boolean
init
private
metaForType
(type, metadata)
If you have some metadata to set for a type
you can call metaForType
.
Parameters:
- type String
- metadata Object
metadataFor
(type)
Object
This method returns the metadata for a specific type.
Parameters:
- type String
Returns:
- Object
modelFor
(key)
subclass of DS.Model
Returns a model class for a particular key. Used by
methods that take a type key (like find
, createRecord
,
etc.)
Parameters:
- key String or subclass of DS.Model
Returns:
- subclass of DS.Model
push
(type, data)
Push some data for a given type into the store.
This method expects normalized data:
- The ID is a key named
id
(an ID is mandatory) - The names of attributes are the ones you used in
your model's
DS.attr
s. - Your relationships must be:
- represented as IDs or Arrays of IDs
- represented as model instances
- represented as URLs, under the
links
key
For this model:
1 2 3 4 5 6 |
App.Person = DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr(), children: DS.hasMany('person') }); |
To represent the children as IDs:
1 2 3 4 5 6 |
{ id: 1, firstName: "Tom", lastName: "Dale", children: [1, 2, 3] } |
To represent the children relationship as a URL:
1 2 3 4 5 6 7 8 |
{ id: 1, firstName: "Tom", lastName: "Dale", links: { children: "/people/1/children" } } |
If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form.
This method can be used both to push in brand new records, as well as to update existing records.
Parameters:
- type String
- data Object
Returns:
- DS.Model the record that was created or updated.
pushMany
(type, datas)
ArrayIf you have an Array of normalized data to push,
you can call pushMany
with the Array, and it will
call push
repeatedly for you.
Parameters:
- type String
- datas Array
Returns:
- Array
pushPayload
(type, payload)
Push some raw data into the store.
The data will be automatically deserialized using the
serializer for the type
param.
This method can be used both to push in brand new records, as well as to update existing records.
You can push in more than one type of object at once. All objects should be in the format expected by the serializer.
1 2 3 4 5 6 7 8 9 10 11 12 |
App.ApplicationSerializer = DS.ActiveModelSerializer; var pushData = { posts: [ {id: 1, post_title: "Great post", comment_ids: [2]} ], comments: [ {id: 2, comment_body: "Insightful comment"} ] } store.pushPayload('post', pushData); |
Parameters:
- type String
- payload Object
recordForId
(type, id)
Returns id record for a given type and ID. If one isn't already loaded,
it builds a new record and leaves it in the empty
state.
Parameters:
- type String
- id String|Integer
Returns:
- DS.Model
recordIsLoaded
(type, id)
Boolean
This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit.
Parameters:
- type
- id String
Returns:
- Boolean
recordWasError
(record)
private
This method is called once the promise returned by an
adapter's createRecord
, updateRecord
or deleteRecord
is rejected (with anything other than a DS.InvalidError
).
Parameters:
- record DS.Model
recordWasInvalid
(record, errors)
private
This method is called once the promise returned by an
adapter's createRecord
, updateRecord
or deleteRecord
is rejected with a DS.InvalidError
.
Parameters:
- record DS.Model
- errors Object
reloadRecord
(record, resolver)
private
This method is called by the record's reload
method. The record's reload
passes in a resolver for the promise it returns.
This method calls the adapter's find
method, which returns a promise. When
that promise resolves, reloadRecord
will resolve the promise returned
by the record's reload
.
Parameters:
- record DS.Model
- resolver Resolver
scheduleSave
(record, resolver)
private
This method is called by record.save
, and gets passed a
resolver for the promise that record.save
returns.
It schedules saving to happen at the end of the run loop.
Parameters:
- record DS.Model
- resolver Resolver
serialize
(record, options)
private
Returns a JSON representation of the record using a custom type-specific serializer, if one exists.
The available options are:
includeId
:true
if the record's ID should be included in the JSON representation
Parameters:
- record DS.Model
- the record to serialize
- options Object
- an options hash
serializerFor
(type)
private
Returns an instance of the serializer for a given type. For
example, serializerFor('person')
will return an instance of
App.PersonSerializer
.
If no App.PersonSerializer
is found, this method will look
for an App.ApplicationSerializer
(the default serializer for
your entire application).
If no App.ApplicationSerializer
is found, it will fall back
to an instance of DS.JSONSerializer
.
Parameters:
- type String
- the record to serialize
typeMapFor
(type)
private
Returns a map of IDs to client IDs for a given type.
Parameters:
- type
unloadAll
(type)
This method unloads all of the known records for a given type.
Parameters:
- type Class
unloadRecord
(record)
For symmetry, a record can be unloaded via the store.
Parameters:
- record DS.Model
updateId
(record, data)
private
When an adapter's createRecord
, updateRecord
or deleteRecord
resolves with data, this method extracts the ID from the supplied
data.
Parameters:
- record DS.Model
- data Object
adapter
{DS.Adapter|String}
The adapter to use to communicate to a backend server or other persistence layer.
This can be specified as an instance, class, or string.
If you want to specify App.CustomAdapter
as a string, do:
1 |
adapter: 'custom'
|
Default: DS.RESTAdapter
defaultAdapter
private
This property returns the adapter, after resolving a possible string key.
If the supplied adapter
was a class, or a String property
path resolved to a class, this property will instantiate the
class.
This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store.
Returns:
- DS.Adapter