For the More Curious: Retrieving Data

As mentioned above, the data store manages model data and knows how to retrieve it. In the previous chapter, you returned data in the SightingRoute model callback with an array. In Chapter 22, you will retrieve model data in this route and return data as a Promise using this.store.findAll and other data retrieval methods.

Below is a table of methods Ember Data’s store object has at its disposal for retrieving data from an API, storing it in memory, and returning it to the requester.

Request type Retrieve all records Retrieve a single record
find persisted and local records findAll findRecord
find local records only peekAll peekRecord
find filtered records query queryRecord

Retrieval methods come in several flavors: persisted and local, local only, and filtered persisted and local. Most use cases call for findAll and findRecord. The arguments for each match closely to the API endpoints that Ember Data will create to request the data from the API.

For findAll, the only required argument is the model name. For example, a request for all the witnesses would be findAll('witness'). Notice the singular name? Remember, this argument is the model name. Ember Data will make sure the request has a plural name when it builds the Ajax URL /witnesses/.

For findRecord, an additional argument is needed to indicate a specific record. This argument is the identifier, usually the id of the record, such as this.store.findRecord('witness', 5). When called, findRecord('witness', 5) will create a request for data at /witnesses/5.

For peekAll and peekRecord, the same arguments are needed to retrieve data. Invoking these methods will return the data immediately, not as a Promise.

Querying your API for data is another way to form requests. If your API supports query parameters, or params, for individual endpoints, Ember Data’s query and queryRecord are great options. Like the other store methods, these methods take the model name as their first argument. The last argument is the query object, whose key/value pairs are converted into query string values. For query, the request will find all records filtered by keys and values. queryRecord is used when you know the request will return a single record.

For example, calling

this.store.query('user',{fName: "todd"})

would produce this request: /users/?f_name=todd. Alternatively,

this.store.queryRecord('user', {email: '[email protected]'})

would produce this request: /[email protected].

All of these store methods leverage adapters, which you will read about in the next chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.218.45