Question

An ember app has the following models.

App.Book = DS.Model.extend
  title = DS.attr('string')
  pages = DS.attr('number')
  chapters = DS.hasMany('bookChapter')

App.BookChapter = DS.Model.extend
  title = DS.attr('string')
  begin = DS.attr('number')
  end   = DS.attr('number')

I do notice that App.Book make request to /api/books and App.BookChapter to /api/bookChapters Is there any way I can make request to /api/books/{id}/chapters or /api/book_chapters?book={id}

I need this to work since I do not authority to change the api endpoint urls.

My ember.js environment is

DEBUG: Ember      : 1.5.0
DEBUG: Ember Data : 1.0.0-beta.7+canary.f482da04
DEBUG: Handlebars : 1.3.0
DEBUG: jQuery     : 1.11.0
Was it helpful?

Solution

The Adapter is responsable to translate store actions against your persistence layer.

As you do not follow the RESTAdapter convention, you will need to create a custom adapter to communicate with your specific API. The easiest way could be to extend RESTAdapter whose implementation is closed to your API.

App.ApplicationAdapter= DS.RESTAdapter.extend({
  namespace: 'api',
  pathForType: function(type) {
    var decamelized = Ember.String.decamelize(type);
    return Ember.String.pluralize(decamelized);
  },
  findQuery: function(store, type, query) {

    var params = [];
    Object.keys(query).forEach(function (key) { 
       var param = key+'='+encodeURIComponent(query[key]);
       params.push(param);
    });
    params = params.join('&');

    var url = this.buildURL(type.typeKey);
    url = [url, params].join('/?');
    return this.ajax(url, 'GET');
  }

});

I ovewrote findQuery, because you do not query by model primary key with find('bookChapter', 1). then you make the request as:

App.ChapterRoute = Ember.Route.extend({
  model: function(params) {
    return this.store.find('bookChapter', {book: params.book_id});
  }
});

If your API differs communication or serialization convention, you would need to extend either the RESTSerializer or RESTAdapter (check the DOCs to know which methods should be overwritten).

Example: http://emberjs.jsbin.com/kocoh/1/edit

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top