injaon
injaon

Reputation: 243

How to use Ember Data serializer wth JQuery AJAX requests?

I've been using Ember-Data very well where my API endpoints are like

domain.com/apples/ => list of apples

domain.com/apples/1/ => Apple with id 1

domain.com/worms/ => list of worms

I need to fetch all the worms in one apple. My API endpoint for this is like

domain.com/apples/1/worms/ => list of worms in apple with id 1

I've been fetching those worms with Em.$.getJSON(...) and works fine. But the result is a list of Object and I want a list of Worm (defined in /models/worms.js)

Upvotes: 1

Views: 112

Answers (1)

Thomas Brus
Thomas Brus

Reputation: 941

Have a look at ember-api-actions.

Your model will then look like this:

// app/models/apple.js
import DS from 'ember-data';
import { memberAction } from 'ember-api-actions';

export default DS.Model.extend({
  // GET /apples/:id/worms
  worms: memberAction({ path: 'worms', type: 'get' })
});

To fetch all worms for a given apple, use something like this:

this.store.findRecord('apple', params.id).then((apple) => apple.worms())

P.S. It's also possible to manually push the JSON response to the ember data store but implementing a custom adapter is more robust (something which you can see is made ridiculously easy by ember-data-actions)

Upvotes: 1

Related Questions