Search code examples
ember-dataember-cli

How to accept model collection metadata, such as count in ember?


In Ember-CLI, how does one go about retrieving/storing model collection metadata?

For example, suppose I have a model 'user' with some defined attributes, and my route retrieves a collection of users with ember-data like so:

  model: function(params) {
    return this.store.findQuery('user', params);
  }
});

and the JSON response from my API looks something like this:

{ users: [{id: 1, name: 'Bob'}, {id: 2, name: 'Joe'}]}

Now, I want to add paging, which means I need a count of total users somewhere in the API response so it looks something like this:

{ user_count: 5,
users: [{id: 1, name: 'Bob'}, {id: 2, name: 'Joe'}]}

That's simple enough, but how do I access user_count from my Ember controller?


Solution

  • So if you are in control of the API then you can use built-in support for metadata provided by Ember Data (using DS.RESTAdapter).

    If you return the following structure from your API:

    {
      "users": [{
        "id": 1,
        "name": "Bob"
      }, 
      {
        "id": 1,
        "name": "Bob"
      }],
      "meta": {
        "user_count": 5
      }
    }
    

    Then you should be able to use:

    var meta = this.store.metadataFor("users");
    

    and access meta.user_count

    There is more information in the Ember Guides (v1.10.0): http://guides.emberjs.com/v1.10.0/models/handling-metadata/

    If you are not in charge of your API you can use a serializer to format the metadata correctly. Let me know if you need more info on that.