DS.Store#queryRecord()

queryRecord (modelName, query) Promise

Defined in addon/-private/system/store.js:1151
Available since 1.13.0

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.

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.get('username');
  console.log(`Currently logged in as ${username}`);
});

The request is made through the adapters' queryRecord:

// app/adapters/user.js
import DS from "ember-data";

export default DS.Adapter.extend({
  queryRecord(modelName, query) {
    return Ember.$.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.get('firstObject');
}).then(function(user) {
  let id = user.get('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) {
  console.log(user); // null
});

Parameters:

modelName String
query Any
an opaque query to be used by the adapter

Returns:

Promise
promise which resolves with the found record or `null`
doc_EmberJs
2016-11-30 16:50:54
Comments
Leave a Comment

Please login to continue.