UNPKG

overmind

Version:
39 lines (38 loc) 2.18 kB
//#region src/rehydrate.ts 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$1) => classInstance(value$1)); 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]; }); } const SERIALIZE = Symbol("SERIALIZE"); const rehydrate = (state, source, classes = {}) => { if (Array.isArray(source)) source.forEach((mutation) => { const pathArray = mutation.path.split(mutation.delimiter); const key = pathArray.pop(); const target = pathArray.reduce((aggr, key$1) => aggr[key$1], state); const classInstance = pathArray.reduce((aggr, key$1) => aggr && aggr[key$1], 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); }; //#endregion export { SERIALIZE, rehydrate }; //# sourceMappingURL=rehydrate.js.map