使用 Ember 数据将 REST 请求发送到嵌套的 API 端点 URL [英] Sending REST requests to a nested API endpoint URL using Ember Data

查看:15
本文介绍了使用 Ember 数据将 REST 请求发送到嵌套的 API 端点 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If you imagine two models defined thus:

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 适配器:

... and a REST Adapter:

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

... 路由设置如下:

... with routing set up like so:

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');
                });
            });
        });
    });
});

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

... and a controller action to save the edited email, which looks like this:

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]

The PUT request is being sent to: http://whatever.com/api/v1/emails/[email_id]

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

However the correct API endpoint is: http://whatever.com/api/v1/users/[user_id]/emails/[email_id]

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

What is the correct way to remedy this issue?

推荐答案

我想出的解决方案只是在 REST 适配器中重写 createRecord、updateRecord 和 deleteRecord.

The solution I came up with was just to rewrite createRecord, updateRecord and deleteRecord in the REST adapter.

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

I added a 'parent' attribute to the models affected. In the *Record hooks, I can check if this is set and edit the path sent to buildURL accordingly.

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

My createRecord, updateRecord and deleteRecord hooks now looks something similar to this:

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");
    }

});

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

The Email model in the example would be something like:

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

这篇关于使用 Ember 数据将 REST 请求发送到嵌套的 API 端点 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆