ken
ken

Reputation: 9013

getting data from non-standard endpoints using ember-data

I have an endpoint /activities which behaves in a typical fashion for a RESTful API using JSON. I can of course do things like the following:

model: function() {
    return this.store.find('activity');
}

to return a list of activities. Or I can:

model: function(params) {
    return this.store.find('activity', params.id);
}

get a specific Activity record. This works fine. But the API also allows certain filtering to be done using URL parameters. So for instance,

GET /activities/type/exercise

Unlike a full list it would only bring back activities which are associated with "exercise". What is the best way for one to pull back data using ember-data? At a bare minimum I want the data to come back, be associated to the correct model, and be iterable via a `DS.RecordArray or similar object.

Ideally I would also like to avoid making network requests every time I hit this route although possibly this is something that I can't get "out of the box". Still interested if there are any best practices.

Upvotes: 2

Views: 188

Answers (1)

Jakeii
Jakeii

Reputation: 1273

Ember can already query for data, by default using query params i.e.

store.find(activities, {type: 'exercise'}); // /activities?type=exercise

you could override findQuery on your activities adapter so that if conforms to your api:

// /adapters/activity.js
import DS form 'ember-data';
export default DS.RESTAdapter.extend({
    findQuery: function(store, type, query) {

        for(var key in query) break; // get first key in the example 'type'
        var path = ['', key, query[key]].join('/');

        return this.ajax(this.buildURL(type.typeKey) + path, 'GET');
    },
});

I haven't tested this but it should work.

Upvotes: 1

Related Questions