Skip to content

Instantly share code, notes, and snippets.

@mschipperheyn
Created April 4, 2016 14:06
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 mschipperheyn/a612dc7e15a5ff28fc91932be2de09eb to your computer and use it in GitHub Desktop.
Save mschipperheyn/a612dc7e15a5ff28fc91932be2de09eb to your computer and use it in GitHub Desktop.
A marshalling function for Normalizr
`
'use strict';
const getEntity = function(id, key, entities){
const ent = entities[key][id];
if(ent === undefined || ent === null){
console.log(`Missing object ${key} ${id}`);
}
return ent;
}
/**
* Marshals a Normalized object back to a full object based on the schema definition
*/
const marshal = function(obj, schema, entities){
if(obj === undefined || obj === null)
return null;
let newObject = {};
for(let key in obj){
if(obj[key] && schema.hasOwnProperty(key)){
//we have a sub schema and a not null value
//we need to see if the key is an array
if(obj[key] instanceof Array){
let aEntities = [];
for(let id of obj[key]){
const ent = getEntity(id, schema[key].getKey(),entities);
aEntities.push(marshal(ent, schema[key],entities));
}
newObject[key] = aEntities;
} else {
const ent = getEntity(obj[key], schema[key].getKey(), entities);
//replace the id with the object from the entities store
newObject[key] = marshal(ent, schema[key],entities);
}
}else{
newObject[key] = obj[key];
}
}
return newObject;
};
export {
marshal
};
`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment