Skip to content

Instantly share code, notes, and snippets.

@andrewhavens
Created April 28, 2016 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewhavens/f9aef6e55da7d1b22ca2b5617ae9417a to your computer and use it in GitHub Desktop.
Save andrewhavens/f9aef6e55da7d1b22ca2b5617ae9417a to your computer and use it in GitHub Desktop.
JSON API compatible Ember Data EmbeddedRecordsMixin
import Ember from 'ember';
var camelize = Ember.String.camelize;
export default Ember.Mixin.create({
// The following is mostly identical to the JSONAPISerializer implementation,
// with the exception of adding an attributes key to the payload.
// https://github.com/emberjs/data/blob/v2.5.2/addon/serializers/json-api.js#L471
serializeHasMany(snapshot, json, relationship) {
var key = relationship.key;
if (this._shouldSerializeHasMany(snapshot, key, relationship)) {
var hasMany = snapshot.hasMany(key);
if (hasMany !== undefined) {
json.relationships = json.relationships || {};
var payloadKey = this._getMappedKey(key, snapshot.type);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, 'hasMany', 'serialize');
}
let data = new Array(hasMany.length);
for (let i = 0; i < hasMany.length; i++) {
let item = hasMany[i];
data[i] = {
type: this.payloadKeyFromModelName(item.modelName),
id: item.id
};
// BEGIN EMBEDDED OVERRIDES
if (this.hasSerializeRecordsOption(key)) {
item.eachAttribute((key, attribute) => {
// TODO: this doesn't check if the attribute is allowed to be serialized, according to this model's serializer
this.serializeAttribute(item, data[i], key, attribute);
});
}
// END EMBEDDED OVERRIDES
}
json.relationships[payloadKey] = { data };
}
}
},
// Identical to the EmbeddedRecordsMixin implementation.
// https://github.com/emberjs/data/blob/v2.5.2/addon/serializers/embedded-records-mixin.js#L411
hasSerializeRecordsOption(attr) {
var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr);
var option = this.attrsOption(attr);
return alwaysEmbed || (option && (option.serialize === 'records'));
},
// Identical to the EmbeddedRecordsMixin implementation.
// https://github.com/emberjs/data/blob/v2.5.2/addon/serializers/embedded-records-mixin.js#L405
hasEmbeddedAlwaysOption(attr) {
var option = this.attrsOption(attr);
return option && option.embedded === 'always';
},
// Identical to the EmbeddedRecordsMixin implementation.
// https://github.com/emberjs/data/blob/v2.5.2/addon/serializers/embedded-records-mixin.js#L438
attrsOption(attr) {
var attrs = this.get('attrs');
return attrs && (attrs[camelize(attr)] || attrs[attr]);
},
});
@andrewhavens
Copy link
Author

I believe the store gets injected into a serializer as this.store so I think you can do this.store.serializerFor('child-model') Source

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