0

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

1 Answer 1

2

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);
    }
3
  • Thanks, I'm gonna give it a try tomorrow. Why the extractSingle-function?
    – Hedge
    Mar 9, 2015 at 17:23
  • Because i assumed your api has the same structure for a request for a single user like /user/<userid>. I guess your api then returns {results { id : user_id, ...} }. If not just change it or skip it, Mar 10, 2015 at 14:21
  • That's what I did. Works perfectly and I learned something. Thank you.
    – Hedge
    Mar 10, 2015 at 21:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.