Best way to add JSON root elements application-wide using RESTSerializer


#1

Hi,

I’ve started to use ember with ember-cli a few days ago and only just getting my bearings with everything, so sorry if this this is going to sound confused …

One of the first things I’ve run into is that the JSON data from the API I’m using does not contain root elements as required by the RESTAdapter. If I understand correctly, the place to override these defaults would be in the RESTSerializer, which is designed to allow custom data munging.

Ideally, I’d like to add root elements both for arrays and individual records for the entire application. I’ve created a app/serializers/application.js file but got a bit stuck with how to achieve what I want.

The RESTSerializer has many methods that seem to fit the bill, such as normalize and extractArray (for multiple records) and extractSingle. Which one would be the most efficient to use to add root elements both to multiple records as well as single records?

Also, how would I implement extractArray, for example, so that I retain the functionality of _super? In the guides I’ve seen this pattern used:

return this._super([args of orig. method]);

The method has this signature: extractArray: function(store, type, payload) whereby type is an instance of DS.Model. How do I get the pluralized name (e.g. ‘posts’ or ‘comments’) to be used as the root element name in the JSON hash from the model instance?

Then I could do something like this?

export default DS.RESTSerializer.extend({
  extractArray: function(store, type, payload) {
    var root = type.nameForRoot; // this doesn't work

    var new_payload = {};
    new_payload[root] = payload;
    return this._super(store, type, payload);
  }
}