using deserializer callback for persistState

This commit is contained in:
FredyC 2015-08-23 13:43:26 +02:00
parent e76bb6956b
commit 6ee3b4373b

View File

@ -1,47 +1,19 @@
export default function persistState(sessionId, parsers) { export default function persistState(sessionId, deserializer = null) {
if (!sessionId) { if (!sessionId) {
return next => (...args) => next(...args); return next => (...args) => next(...args);
} }
function callParser(parserMethod, parserName, stateSlice) { function deserializeState(fullState) {
const parser = parsers[parserName]; if (!fullState || typeof deserializer !== 'function') {
if (parser && typeof parser[parserMethod] === 'function') {
return parser[parserMethod](stateSlice);
}
return stateSlice;
}
// function serializeState(state) {
// if (!state) {
// return state;
// }
// return Object.keys(state).reduce((serialized, sliceName) => {
// serialized[sliceName] = callParser('serialize', sliceName, state[sliceName]);
// return serialized;
// }, {});
// }
function deserializeState(state) {
if (!state) {
return state;
}
return Object.keys(state).reduce((deserialized, sliceName) => {
deserialized[sliceName] = callParser('deserialize', sliceName, state[sliceName]);
return deserialized;
}, {});
}
function parseState(fullState) {
if (!fullState || !parsers) {
return fullState; return fullState;
} }
return { return {
...fullState, ...fullState,
committedState: deserializeState(fullState.committedState), committedState: deserializer(fullState.committedState),
computedStates: fullState.computedStates.map((computedState) => { computedStates: fullState.computedStates.map((computedState) => {
return { return {
...computedState, ...computedState,
state: deserializeState(computedState.state) state: deserializer(computedState.state)
}; };
}) })
}; };
@ -52,7 +24,7 @@ export default function persistState(sessionId, parsers) {
let finalInitialState; let finalInitialState;
try { try {
finalInitialState = parseState(JSON.parse(localStorage.getItem(key))) || initialState; finalInitialState = deserializeState(JSON.parse(localStorage.getItem(key))) || initialState;
next(reducer, initialState); next(reducer, initialState);
} catch (e) { } catch (e) {
console.warn('Could not read debug session from localStorage:', e); console.warn('Could not read debug session from localStorage:', e);