import { Action, Reducer } from "redux"; import { ReduxBackupPayload, ReduxBackupAction, types, Store, RestoreHandler } from "./types"; import { initStore } from "./storage"; const getPayload = (action: Action): ReduxBackupPayload => { const backupAction = action as ReduxBackupAction; return backupAction.payload; } const mapActionTypeToStoreFunction = (store: Store) => { const map = { [types.BACKUP]: store.backup, [types.DELETE]: store.deleteBackup, [types.RESTORE]: store.restore, } return (action: TAction): RestoreHandler => map[action.type]; } function handleReduxBackupAction(reducerName: string, _store?: Store) { const store = initStore(reducerName, _store); const getStoreFunctionByAction = mapActionTypeToStoreFunction(store); return (state: TState, action: TAction): TState | undefined => { const storeFunction = getStoreFunctionByAction(action); return storeFunction ? storeFunction(state, getPayload(action)) : undefined; } } function reducer(reducer: Reducer, reducerName: string, store?: Store): Reducer { let reduxBackupActionHandler = handleReduxBackupAction(reducerName, store); return (state: TS, action: TA): TS => { const nextState = reduxBackupActionHandler(state, action); return nextState || reducer(state, action); } } export const withBackup = reducer;