Skip to content

Instantly share code, notes, and snippets.

@rsutphin
Created December 5, 2014 21:44
Show Gist options
  • Save rsutphin/3252dfd221157d557a0b to your computer and use it in GitHub Desktop.
Save rsutphin/3252dfd221157d557a0b to your computer and use it in GitHub Desktop.
Application serializer for an ember-cli / ember-pouch project to resolve ember-pouch #16
import Ember from 'ember';
/*globals EmberPouch*/
export default EmberPouch.Serializer.extend({
/**
* Copied from JSONSerializer to enable default serialization of the hasMany
* side of manyToOne relationships. It is not clear to me why this is not the
* default — it seems to make it impossible to ever load the many from the one —
* but there is plentiful evidence that it's not going to be changed:
*
* - https://github.com/emberjs/data/commit/7f752ad15eb9b9454e3da3f4e0b8c487cdc70ff0#comments
* - https://github.com/emberjs/data/issues/2068
* - https://github.com/emberjs/data/pull/1678
*
* The supported solution is to use a custom serializer for each model and
* explicitly indicate which hasMany relationships should be embedded as IDs.
* No thank you.
*/
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
if (this._canSerialize(key)) {
var payloadKey;
// if provided, use the mapping provided by `attrs` in
// the serializer
payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, "hasMany");
}
var relationshipType = record.constructor.determineRelationshipType(relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany' || relationshipType === 'manyToOne') {
json[payloadKey] = Ember.get(record, key).mapBy('id');
// TODO support for polymorphic manyToNone and manyToMany relationships
}
}
}
});
@rsutphin
Copy link
Author

rsutphin commented Dec 5, 2014

Make this app/serializers/application.js in your ember-pouch project (or target it at separate models, if that's appropriate for your app).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment