1 import type { Action } from 'redux';
3 import type { HistoryItem, OptimisticReducersMapObject, WrappedOptimisticState } from '../types';
4 import { isCombinedOptimisticReducer } from './assertions';
6 export const wrapOptimisticState = <T>(state: T): WrappedOptimisticState<T> => ({
8 optimistic: { history: [] },
11 export const unwrapOptimisticState = <T>(state: WrappedOptimisticState<T>): T => {
12 const { optimistic, ...inner } = state;
15 * TS: 'T' could be instantiated with an arbitrary type which could be unrelated to
16 * 'Omit<WrappedOptimisticState<T>, "optimistic">'
18 * Impossible, since WrappedOptimisticState<T> is 'T & { optimistic: {...} }'
20 return inner as any as T;
23 /* Unwraps the underlying actionfrom an OptimisticHistoryItem */
24 export const getActionFromHistoryItem = (item: HistoryItem): Action => item.action;
27 * Sanitizes an optimistic reducer map object by recursively
28 * unwrapping any combined optimistic reducer into a sub-map
29 * of the inner reducers (see combineOptimisticReducers)
31 export const sanitizeOptimisticReducerMapObject = (map: OptimisticReducersMapObject): OptimisticReducersMapObject => {
32 return Object.fromEntries(
33 Object.entries(map).map(([reducerKey, reducer]) => {
35 typeof reducer === 'function' &&
36 isCombinedOptimisticReducer(reducer) &&
37 reducer.innerCombinedReducers !== undefined
39 return [reducerKey, sanitizeOptimisticReducerMapObject(reducer.innerCombinedReducers)];
42 return [reducerKey, reducer];