|
| 1 | +import _ from 'lodash'; |
| 2 | +import { Action, PreloadedState, Reducer, StoreEnhancer } from 'redux'; |
| 3 | +import { LiftedState } from '@redux-devtools/instrument'; |
| 4 | + |
| 5 | +export default function persistState< |
| 6 | + S, |
| 7 | + A extends Action<unknown>, |
| 8 | + MonitorState |
| 9 | +>( |
| 10 | + sessionId?: string | null, |
| 11 | + deserializeState: (state: S) => S = _.identity, |
| 12 | + deserializeAction: (action: A) => A = _.identity |
| 13 | +): StoreEnhancer { |
| 14 | + if (!sessionId) { |
| 15 | + return (next) => |
| 16 | + (...args) => |
| 17 | + next(...args); |
| 18 | + } |
| 19 | + |
| 20 | + function deserialize( |
| 21 | + state: LiftedState<S, A, MonitorState> |
| 22 | + ): LiftedState<S, A, MonitorState> { |
| 23 | + return { |
| 24 | + ...state, |
| 25 | + actionsById: _.mapValues(state.actionsById, (liftedAction) => ({ |
| 26 | + ...liftedAction, |
| 27 | + action: deserializeAction(liftedAction.action), |
| 28 | + })), |
| 29 | + committedState: deserializeState(state.committedState), |
| 30 | + computedStates: state.computedStates.map((computedState) => ({ |
| 31 | + ...computedState, |
| 32 | + state: deserializeState(computedState.state), |
| 33 | + })), |
| 34 | + }; |
| 35 | + } |
| 36 | + |
| 37 | + return (next) => |
| 38 | + <S2, A2 extends Action<unknown>>( |
| 39 | + reducer: Reducer<S2, A2>, |
| 40 | + initialState?: PreloadedState<S2> |
| 41 | + ) => { |
| 42 | + const key = `redux-dev-session-${sessionId}`; |
| 43 | + |
| 44 | + let finalInitialState; |
| 45 | + try { |
| 46 | + const json = localStorage.getItem(key); |
| 47 | + if (json) { |
| 48 | + finalInitialState = |
| 49 | + deserialize(JSON.parse(json) as LiftedState<S, A, MonitorState>) || |
| 50 | + initialState; |
| 51 | + next(reducer, initialState); |
| 52 | + } |
| 53 | + } catch (e) { |
| 54 | + console.warn('Could not read debug session from localStorage:', e); // eslint-disable-line no-console |
| 55 | + try { |
| 56 | + localStorage.removeItem(key); |
| 57 | + } finally { |
| 58 | + finalInitialState = undefined; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + const store = next( |
| 63 | + reducer, |
| 64 | + finalInitialState as PreloadedState<S2> | undefined |
| 65 | + ); |
| 66 | + |
| 67 | + return { |
| 68 | + ...store, |
| 69 | + dispatch<T extends A2>(action: T) { |
| 70 | + store.dispatch(action); |
| 71 | + |
| 72 | + try { |
| 73 | + localStorage.setItem(key, JSON.stringify(store.getState())); |
| 74 | + } catch (e) { |
| 75 | + console.warn('Could not write debug session to localStorage:', e); // eslint-disable-line no-console |
| 76 | + } |
| 77 | + |
| 78 | + return action; |
| 79 | + }, |
| 80 | + }; |
| 81 | + }; |
| 82 | +} |
0 commit comments