Hedge
Hedge

Reputation: 16748

Customize JSON collection name in Serializer

When accessing API resources like /api/users/ which list/search a resource Ember Data expectects the response to be in this format:

{
  "users": [{
    "name": "Rails"
  }, {
    "name": "Omakase"
  }]
}

but my response looks like this:

{
  "results": [{
    "name": "Rails"
  }, {
    "name": "Omakase"
  }]
}

How can I tell my Serializer to turn results into users?

The following Serialzer renames single attributes but not the whole list as shown above:

import DS from 'ember-data';

export default DS.ActiveModelSerializer.extend({
  attrs: {
    "users" : "results",
  }
});

Upvotes: 0

Views: 97

Answers (1)

ahmed.hoban
ahmed.hoban

Reputation: 516

this should do it for you, dont change attributes, just these two methods for extracting single models and arrays of models. You take the payload.results property and process it further, instead of the default payload.

    extractArray: function(store, type, payload) {
        return Array.prototype.map.call(payload.results, function(hash) {
            return this.normalize(type, hash, payload.type);
        }, this);
    },

    extractSingle: function(store, type, payload, recordId) {
        return this.normalize(type, payload.results, payload.type);
    }

Upvotes: 2

Related Questions