UNPKG

overmind

Version:
74 lines 2.97 kB
export function rehydrateState(target, source, classes = {}) { if (!target || !source) { throw new Error(`You have to pass a "target" and "source" object to rehydrate`); } Object.keys(source).forEach((key) => { const value = source[key]; const classInstance = classes[key]; if (typeof classInstance === 'function' && Array.isArray(target[key])) { target[key] = source[key].map((value) => classInstance(value)); } else if (typeof classInstance === 'function' && typeof target[key] === 'object' && target[key] !== null && target[key].constructor.name === 'Object') { target[key] = Object.keys(source[key]).reduce((aggr, subKey) => { aggr[subKey] = classInstance(source[key][subKey]); return aggr; }, {}); } else if (typeof classInstance === 'function') { target[key] = classInstance(source[key]); } else if (typeof value === 'object' && !Array.isArray(value) && value !== null) { if (!target[key]) target[key] = {}; rehydrateState(target[key], source[key], classes[key]); } else { target[key] = source[key]; } }); } export const SERIALIZE = Symbol('SERIALIZE'); export const rehydrate = (state, source, classes = {}) => { if (Array.isArray(source)) { const mutations = source; mutations.forEach((mutation) => { const pathArray = mutation.path.split(mutation.delimiter); const key = pathArray.pop(); const target = pathArray.reduce((aggr, key) => aggr[key], state); const classInstance = pathArray.reduce((aggr, key) => aggr && aggr[key], classes); if (mutation.method === 'set') { if (typeof classInstance === 'function' && Array.isArray(mutation.args[0])) { target[key] = mutation.args[0].map((arg) => classInstance(arg)); } else if (typeof classInstance === 'function') { target[key] = classInstance(mutation.args[0]); } else { target[key] = mutation.args[0]; } } else if (mutation.method === 'unset') { delete target[key]; } else { target[key][mutation.method].apply(target[key], typeof classInstance === 'function' ? mutation.args.map((arg) => { return typeof arg === 'object' && arg !== null ? classInstance(arg) : arg; }) : mutation.args); } }); } else { rehydrateState(state, source, classes); } }; //# sourceMappingURL=rehydrate.js.map