Skip to content

Instantly share code, notes, and snippets.

@nickschot
Last active August 29, 2015 14:25
Show Gist options
  • Save nickschot/9c6f5548682db2ecde68 to your computer and use it in GitHub Desktop.
Save nickschot/9c6f5548682db2ecde68 to your computer and use it in GitHub Desktop.
JSON API serializer for Ember to make ID's generated by FortuneJS URL safe
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
serializeIdFunc: decodeURIComponent,
normalizeIdFunc: encodeURIComponent,
/*
@method normalize
@param {DS.Model} modelClass
@param {Object} resourceHash
@return {String}
*/
normalize: function(modelClass, resourceHash) {
var result = this._super(modelClass, resourceHash);
var data = this._applyToId(result.data, this.normalizeIdFunc);
return { data };
},
/**
@method serialize
@param {DS.Snapshot} snapshot
@param {Object} options
@return {Object} json
*/
serialize: function(snapshot, options) {
var result = this._super(snapshot, options);
var data = this._applyToId(result.data, this.serializeIdFunc);
return { data };
},
/**
* Applies a function to all id properties in the data object (including relationships)
* @param data A data object per JSON API specification
* @param fn The prototype of the String transformation function to apply
* @private
*/
_applyToId: function(data, fn){
var fnContext = {};
if(data.id){
data.id = fn.apply(fnContext, [data.id]);
}
var relationships = data.relationships || {};
Object.keys(relationships).forEach(function(key){
var relationship = relationships[key];
if(relationship.data && relationship.data.constructor === Array){
relationship.data.forEach(function(relData){
if(relData.id){
relData.id = fn.apply(fnContext, [relData.id]);
}
});
} else {
var data = relationship.data;
if(data && data.id){
data.id = fn.apply(fnContext, [data.id]);
}
}
});
return data;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment