Last active
December 24, 2015 14:59
-
-
Save slindberg/6817234 to your computer and use it in GitHub Desktop.
Ember data serializer that normalizes embedded records without ids
This file contains hidden or 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
App.ApplicationSerializer = DS.RESTSerializer.extend({ | |
// Extract embedded relations from the payload and load them into the store | |
normalizeRelationships: function(type, hash) { | |
var store = this.store; | |
this._super(type, hash); | |
type.eachRelationship(function(attr, relationship) { | |
var relatedTypeKey = relationship.type.typeKey; | |
if (relationship.options.embedded) { | |
if (relationship.kind === 'hasMany') { | |
hash[attr] = hash[attr].map(function(embeddedHash) { | |
// Normalize the record with the correct serializer for the type | |
var normalized = store.serializerFor(relatedTypeKey).normalize(relationship.type, embeddedHash, attr); | |
// If the record has no id, give it a GUID so relationship management works | |
if (!normalized.id) { | |
normalized.id = Ember.generateGuid(null, relatedTypeKey); | |
} | |
// Push the record into the store | |
store.push(relatedTypeKey, normalized); | |
// Return just the id, and the relation manager will take care of the rest | |
return normalized.id; | |
}); | |
} | |
} | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment