samedi 23 avril 2016

EmberJS RESTSerializer with embedded hasMay relationship

I have simple api that returns channels, and each channel contains a number of stories. The API returns the following structure for a channel:

{
    "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"
        }
    ]
}

I have the two following models defined, channel.js:

import DS from 'ember-data';

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

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

I also have this RESTSerializer to deserialize a channel:

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

The code above works but it will make a new request to the server for each story in the channel, but since the data is already included in the response there is no need for those extra requests. If I leave the story data as-in then normalizing the data will fail.

Is there a way to indicated that the data for related models is embedded in the response?




Aucun commentaire:

Enregistrer un commentaire