korCZis
korCZis

Reputation: 580

Return count of total rows in ember data `find` or `findAll` request

I need to know how many rows of a specific resource (App.User) exist in total.

I tried to return it in response, but Ember complains about not mapped properties and is expecting only array of records (users: [ "john", "fred"]). I do not want to make an additional query to the server.

Is there any clean way to achieve this with Ember?

Upvotes: 8

Views: 4329

Answers (3)

demee
demee

Reputation: 582

I have solved this problem by implementing handleResponse in my adapter and modifying the response in the way that Ember expects it.

Let's say I get a response from server similar to this:

{
  "count": 203,
  "users": {...} //user data conforming to model 
} 

My handleResponse implementation looks like this:

handleResponse (status, headers, payload, requestData) {
  let parsedPayload = {
    users: payload.users,
    meta: {
      total: payload.count
    }
  };
  return this._super(status, headers, parsedPayload, requestData);
}

Then I can get the model metadata in a way Ember documentation specifies it

Upvotes: 0

Robin Clowers
Robin Clowers

Reputation: 2160

If you want this in a handlebars template, you can do {{this.length}}.

Upvotes: 4

inertia
inertia

Reputation: 404

You need not make an additional query to the server. Once you get the data in datastore from the server, it stays there unless some record is dirty and you run a store.commit

So, after you get your records by saying

users = App.User.find()

you can simply do users.get('length') and you will get the length. When you do this, an additional query to the server is not generated.

Upvotes: 4

Related Questions