-
-
Save hashg/c9a5fcc9a85795b969c6 to your computer and use it in GitHub Desktop.
Ember Data serializer example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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