Created
April 4, 2016 14:06
-
-
Save mschipperheyn/a612dc7e15a5ff28fc91932be2de09eb to your computer and use it in GitHub Desktop.
A marshalling function for Normalizr
This file contains 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
` | |
'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