Hedge
Hedge

Reputation: 16768

Retrieve count (total) from non-default REST API

I would like to query my server for this URL http://localhost:1337/api/posts/count?category=technology using Ember. I'm using the default RESTAdapter like this:

export default DS.RESTAdapter.extend({
  coalesceFindRequests: true,
  namespace: 'api',
)};

The Post model looks like this:

import DS from 'ember-data';

var Post = DS.Model.extend({
  title: DS.attr('string'),
  permalink: DS.attr('string'),
  body: DS.attr('string')
});

export default Post;

How do I make such a request?

Upvotes: 0

Views: 309

Answers (1)

andrusieczko
andrusieczko

Reputation: 2824

I think you have at least two ways to achieve that when you don't have a control over your backend. Otherwise, you can still use the RESTful API (see the last section of my answer).

Override buildURL

The first one is to use the existing RESTAdapter functionalities and only override the buildURL method:

var PostAdapter = DS.RESTAdapter.extend({
  namespace: 'api',

  buildURL: function(type, id, record) {
    var originalUrl = this._super(type, id, record);
    if (this._isCount(type, id, record))  { // _isCount is your custom method
      return originalUrl + '/count';
    }
    return originalUrl;
  }
});

where in the _isCount method you decide (according to record property for example) if it's what you want. And then, you can pass the params using the store:

this.store.find('post', {
  category: technology
});

Override findQuery

The second way is to override the whole findQuery method. You can either use the aforementioned DS.RESTAdapter or use just DS.Adapter. The code would look as the following:

var PostAdapter = DS.Adapter.extend({
  namespace: 'api',

  findQuery: function(store, type, query) {
    // url be built smarter, I left it for readability
    var url = '/api/posts/count';

    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.$.getJSON(url, query).then(function(data) {
        Ember.run(null, resolve, data);
      }, function(jqXHR) {
        jqXHR.then = null;
        Ember.run(null, reject, jqXHR);
      });
    });
  },

});

and you use the store as in the previous example as well:

this.store.find('post', {
  category: technology
});

Obtaining 'count' from meta

If you have a complete control on your backend, you can leverage the power of metadata.

The server response then would be:

// GET /api/posts/:id
{
  "post": {
    "id": "my-id",
    "title": "My title",
    "permalink": "My permalink",
    "body": "My body"
  },

  "meta": {
    "total": 100
  }
} 

and then you can obtain all the meta information from:

this.store.metadataFor("post");

Similarly, you can use this approach when getting all the posts from /api/posts.

I hope it helps!

Upvotes: 3

Related Questions