Skip to content

Instantly share code, notes, and snippets.

@ancyrweb
Created January 21, 2017 11:37
Show Gist options
  • Save ancyrweb/42236403a0ad1f6091b476707bf00f29 to your computer and use it in GitHub Desktop.
Save ancyrweb/42236403a0ad1f6091b476707bf00f29 to your computer and use it in GitHub Desktop.
Normalize deeply
import * as normalizr from 'normalizr';
/**
* Given an object where keys are IDs
* Return all the objects and an array of unique IDs
*
* @param object
* @returns {{entities: {}, result: Array}}
*/
export const shallowNormalize = (object) => {
let ids = [];
if(object['undefined']){
delete object['undefined'];
}
for(let key in object){
if(!object.hasOwnProperty(key)){
continue;
}
ids.push(parseInt(key, 10));
}
return {
entities: object,
result: ids
}
};
/**
* Given an object containing multiple objects where keys are IDs
* Return all the objects and an other object where the name of every
* entities holds an array of IDs.
*
* @param originalSchemaName
* @param normalized
* @returns {{entities: {}, result: {}}}
*/
export const deepNormalize = (originalSchemaName, normalized) => {
const result = {};
const entities = {};
const normalizedEntities = normalized.entities;
for (let entity in normalizedEntities) {
if (!entity || !normalizedEntities.hasOwnProperty(entity)) {
continue;
}
entities[entity] = normalizedEntities[entity];
if (entity === originalSchemaName) {
result[entity] = Array.isArray(normalized.result) ? normalized.result : [normalized.result];
} else {
const obj = shallowNormalize(normalizedEntities[entity]);
result[entity] = obj.result;
}
}
return {
entities: entities,
result: result
}
};
/**
* Normalize the data with a schema.
* @param data
* @param config
* @returns {{entities, result}|{entities: {}, result: {}}}
*/
export const normalize = (data, config) => {
return deepNormalize(config.originalSchemaName, normalizr.normalize(data, config.schema));
};
export const dataSchema = (schema, originalSchemaName) => ({
schema,
originalSchemaName
});
export const arrayOf = (schema) => normalizr.arrayOf(schema);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment