EmberJS RESTSerializer与嵌入的hasMay关系

时间:2016-04-24 03:36:38

标签: javascript ember.js ember-data

我有简单的api返回频道,每个频道都包含许多故事。 API为频道返回以下结构:

{
    "id": 1,
    "name": "The Awesome Channel",
    "stories": [
        {
            "icon": null,
            "id": 3,
            "pub_date": "2015-08-08T17:32:00.000Z",
            "title": "First Cool Story"
        },
        {
            "icon": null,
            "id": 4,
            "pub_date": "2015-10-20T12:24:00.000Z",
            "title": "Another Cool Story"
        }
    ]
}

我定义了以下两个模型,channel.js

import DS from 'ember-data';

export default DS.Model.extend({
    name: DS.attr('string'),
    bgurl: DS.attr('string'),
    stories: DS.hasMany('story')
});

story.js

import DS from 'ember-data';

export default DS.Model.extend({
    channelId: DS.attr('number'),
    title: DS.attr('string'),
    pubDate: DS.attr('string'),
    icon: DS.attr('string'),
});

我也有这个RESTSerializer来反序列化一个频道:

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
    normalizeArrayResponse(store, primaryModelClass, hash, id, requestType) {
        var newHash = {
            channels: hash
        };
        return this._super(store, primaryModelClass, newHash, id, requestType);
    },

     normalizeSingleResponse(store, primaryModelClass, hash, id, requestType) {
        // Convert embedded data into a lost of story ids
        var stories = hash.stories.map(function(story) {
            return story.id;
        });
        delete hash.stories;
        hash.stories = stories;
        var newHash = {
            channel: hash,
        };
        return this._super(store, primaryModelClass, newHash, id, requestType);
    }
});

上面的代码可以工作,但它会为通道中的每个故事向服务器发出新的请求,但由于数据已包含在响应中,因此不需要这些额外的请求。如果我将故事数据保留为原样,则规范化数据将失败。

有没有办法表明相关模型的数据是否嵌入在响应中?

1 个答案:

答案 0 :(得分:1)

您是否尝试将故事声明为频道序列化程序中的内容?

export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
  attrs: {
    stories: { embedded: 'always' }
  },

  normalizeArrayResponse(store, primaryModelClass, hash, id, requestType) {

  ...
});