使用Ember Data将REST请求发送到嵌套的API端点URL

时间:2014-02-03 15:12:35

标签: ember.js ember-data

如果你想象这样定义了两个模型:

App.User = DS.Model.extend({
    emails: DS.hasMany('email', {embedded: 'always'}),
});

App.Email = DS.Model.extend({
    address: DS.attr('string'),
    alias: DS.attr('string'),
    user: DS.belongsTo('user')
});

...和REST适配器:

App.UserAdapter = DS.RESTAdapter.extend({
    url: 'http://whatever.com',
    namespace: 'api/v1'
});

...路由设置如下:

App.Router.map(function () {
    this.route('index', { path: '/' });
    this.resource('users', function () {
        this.route('index');
        this.route('add');
        this.resource('user', { path: ':user_id' }, function () {
            this.route('delete');
            this.route('edit');
            this.resource('emails', function () {
                this.route('index');
                this.route('add');
                this.resource('email', { path: ':email_id' }, function () {
                    this.route('delete');
                    this.route('edit');
                });
            });
        });
    });
});

...以及用于保存已编辑电子邮件的控制器操作,如下所示:

App.EmailEditController = Ember.ObjectController.extend({
    actions: {
        save: function () {
            var self = this;
            var email = this.get('model');
            email.save().then(function(){
                self.transitionToRoute('email', email);
            });
        }
    }
});

问题是这个......

PUT请求正在发送到:http://whatever.com/api/v1/emails/[email_id]

但正确的API端点是:http://whatever.com/api/v1/users/[user_id]/emails/[email_id]

解决此问题的正确方法是什么?

2 个答案:

答案 0 :(得分:5)

我提出的解决方案只是在REST适配器中重写createRecord,updateRecord和deleteRecord。

我为受影响的模型添加了“父”属性。在* Record钩子中,我可以检查是否已设置并相应地编辑发送到buildURL的路径。

我的createRecord,updateRecord和deleteRecord挂钩现在看起来类似于:

App.UserAdapter = DS.RESTAdapter.extend({

    createRecord: function (store, type, record) {

        if (!record.get('parent') || null === record.get('parent')) {
            return this._super(store, type, record);
        }

        var data = {};
        var serializer = store.serializerFor(type.typeKey);

        var parent_type = record.get('parent');
        var parent_id = record.get(parent_type).get('id');
        var child_type = Ember.String.camelize(
            Ember.String.pluralize(
                type.typeKey.split(
                    record.get('parent')
                ).pop()
            )
        );

        var path = Ember.String.pluralize(parent_type) + '/' + parent_id + '/' + child_type;

        serializer.serializeIntoHash(data, type, record, { includeId: true });

        return this.ajax(this.buildURL(path), "POST", { data: data });
    },

    updateRecord: function(store, type, record) {

        if(!record.get('parent') || null === record.get('parent')){
            return this._super(store, type, record);
        }

        var data = {};
        var serializer = store.serializerFor(type.typeKey);

        var parent_type = record.get('parent');
        var parent_id = record.get(parent_type).get('id');
        var child_type = Ember.String.camelize(
            Ember.String.pluralize(
                type.typeKey.split(
                    record.get('parent')
                ).pop()
            )
        );

        var path = Ember.String.pluralize(parent_type) + '/' + parent_id + '/' + child_type;

        serializer.serializeIntoHash(data, type, record);
        var id = record.get('id');

        return this.ajax(this.buildURL(path, id), "PUT", { data: data });
    },

    deleteRecord: function (store, type, record) {

        if (!record.get('parent')) {
            return this._super(store, type, record);
        }

        var parent_type = record.get('parent');
        var parent_id = record.get('parent_id');
        var child_type = Ember.String.camelize(
            Ember.String.pluralize(
                type.typeKey.split(
                    record.get('parent')
                ).pop()
            )
        );

        var path = Ember.String.pluralize(parent_type) + '/' + parent_id + '/' + child_type;
        var id = record.get('id');

        return this.ajax(this.buildURL(path, id), "DELETE");
    }

});

示例中的电子邮件模型类似于:

App.Email = DS.Model.extend({
    address: DS.attr('string'),
    alias: DS.attr('string'),
    user: DS.belongsTo('user'),
    parent: 'user'
});

答案 1 :(得分:4)

我通过在需要时覆盖模型特定适配器中的buildURL方法解决了这个问题,使用mixin来封装方法。基本上,它使用默认方法来获取根据Ember规则构建的URL,然后切片并放置其他信息。当然,这是有效的,因为在buildURL我们可以访问record ...

以下是CoffeeScript的基本概念:

module.exports = App.RestWithParentMixin = Ember.Mixin.create
  host: App.Environment.get('hostREST')
  namespace: App.Environment.get('apiNamespace')
  ancestorTypes: null

  buildURL: (type, id, record) ->
    url = @_super(type, id, record)
    ancestorTypes = @get('ancestorTypes')
    if ancestorTypes == null
        urlFixed = url
    else
        urlPrefix = @urlPrefix()
        urlWithoutPrefix = url.slice(urlPrefix.length)
        ancestry = []
        ancestorTypes
        if not Array.isArray(ancestorTypes)
            ancestorTypes = [ancestorTypes]
        for ancestorType in ancestorTypes
            ancestor = record.get(ancestorType)
            ancestorID = ancestor.get('id')
            ancestry.push(ancestorType)
            ancestry.push(ancestorID)
        urlFixed = urlPrefix + '/' + ancestry.join('/') + urlWithoutPrefix
    urlFixed

PS:添加一个小编辑,我使用的是Ember 1.7.1和Ember Data 1.0.0-beta.11