From e76bb6956bce791c1eee2466694a68112adbd9c7 Mon Sep 17 00:00:00 2001 From: FredyC Date: Wed, 19 Aug 2015 21:58:25 +0200 Subject: [PATCH] custom parsers for persistState --- src/persistState.js | 48 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/src/persistState.js b/src/persistState.js index 09a6d598..ecab0a54 100644 --- a/src/persistState.js +++ b/src/persistState.js @@ -1,14 +1,58 @@ -export default function persistState(sessionId) { +export default function persistState(sessionId, parsers) { if (!sessionId) { return next => (...args) => next(...args); } + function callParser(parserMethod, parserName, stateSlice) { + const parser = parsers[parserName]; + 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, + committedState: deserializeState(fullState.committedState), + computedStates: fullState.computedStates.map((computedState) => { + return { + ...computedState, + state: deserializeState(computedState.state) + }; + }) + }; + } + return next => (reducer, initialState) => { const key = `redux-dev-session-${sessionId}`; let finalInitialState; try { - finalInitialState = JSON.parse(localStorage.getItem(key)) || initialState; + finalInitialState = parseState(JSON.parse(localStorage.getItem(key))) || initialState; next(reducer, initialState); } catch (e) { console.warn('Could not read debug session from localStorage:', e);