Skip to content

Instantly share code, notes, and snippets.

@hashg
Forked from marbemac/gist:06c5040e4d71694f07b3
Last active August 29, 2015 14:06
Show Gist options
  • Save hashg/c9a5fcc9a85795b969c6 to your computer and use it in GitHub Desktop.
Save hashg/c9a5fcc9a85795b969c6 to your computer and use it in GitHub Desktop.
Ember Data serializer example
// API return format is as so:
// {
// data: [
// {
// name: 'foo'
// },
// {
// name: 'bar'
// }
// ]
// }
// Ember expects:
// {
// posts: [
// {
// name: 'foo'
// },
// {
// name: 'bar'
// }
// ]
// }
import Ember from 'ember';
import DS from "ember-data";
export default DS.RESTSerializer.extend({
// Custom json root. The API returns objects in the "data" key.
// We need to re-assign it to the singular version of the model name.
// So {data: {name: foo}} becomes {post: {name: foo}}
extractSingle: function(store, primaryType, rawPayload, recordId) {
var typeKey = primaryType.typeKey;
payload[typeKey] = payload['data'];
delete payload['data'];
return this._super(store, primaryType, rawPayload, recordId);
},
// Custom json root. The API returns objects in the "data" key.
// We need to re-assign it to the plural version of the model name.
// So {data: [{post1}, {post2}]} becomes {posts: [{post1},{post2}]}
extractArray: function(store, primaryType, payload) {
var pluralTypeKey = Ember.Inflector.inflector.pluralize(primaryType.typeKey);
payload[pluralTypeKey] = payload['data'];
delete payload['data'];
return this._super(store, primaryType, payload);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment