Custom REST url for specific Model

2020-07-16 03:03发布

问题:

Is there a way in Ember to configure a custom REST url for a specific Model?

Like with this model:

App.Post = DS.Model.extend({
    title: DS.attr('string'),
    comments: DS.hasMany('App.Comment')
});
App.Comment = DS.Model.extend({
    content: DS.attr('string'),
    post: DS.belongsTo('App.Post')
});

And this Store:

app.Store = DS.Store.extend({
    revision : 11,
    adapter : DS.RESTAdapter.extend({
        namespace : 'rest'
    })
});

I want that the comments are retrieved via /rest/post/{id}/comments instead of /rest/comments which is the default behaviour.
Is it possible to configure a rest-url for one specific Model?

回答1:

You can register an additional adapter and 'scope' it to your model.

App.Store.registerAdapter('App.Post', DS.RESTAdapter.extend({
  url: "/rest/post/"
}));


回答2:

Is this for literally just for one model across your entire app or is this the default "hasMany" uri that your REST backend uses? I ask because my api (django rest framework) uses this exact uri and it required a full blown pull request on the ember-data project because to build the URL the adapter needs the related "parent" or "owner" (something rails devs never needed so it didn't exist).

I would write your own adapter (just subclass the base adapter so you only override the single hasMany that is different). The method I wrote for my adapter is below and here is my full blown adapter for reference.

This is ember-data revision 11 friendly btw (have not upgraded to 12 yet)

https://github.com/toranb/ember-data-django-rest-adapter/blob/master/tests/adapter.js

    findMany: function(store, type, ids, parent) {
        var json = {}
        , root = this.rootForType(type)
        , plural = this.pluralize(root)
        , ids = this.serializeIds(ids)
        , url = this.buildFindManyUrlWithParent(store, type, ids, parent);

        this.ajax(url, "GET", {
            success: function(pre_json) {
                json[plural] = pre_json;
                Ember.run(this, function(){
                    this.didFindMany(store, type, json);
                });
            }
        });
    },