All files create-staterx.ts

100% Statements 58/58
100% Branches 25/25
100% Functions 12/12
100% Lines 52/52

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 1986x 6x                     6x   6x                                                                   6x 58x 58x         58x 58x   58x   5x     58x   58x       14x 14x   4x           6x 58x 58x 58x 58x           58x 38x   38x   14x   4x   20x     20x       6x                                       116x 116x 120x       58x 58x 58x 58x 58x     58x   58x   58x         58x           58x   58x                 58x 2x         58x 38x       58x   58x                             58x   58x   58x    
import { BehaviorSubject, Observable, Subject, merge } from 'rxjs';
import {
  AnyAction,
  genRandomString,
  createConstants,
  Reducer,
  Constants,
  Dispatcher,
  DispatchersList,
  wrapDispatchSubject,
  Dispatch
} from './utils';
import { distinctUntilChanged, map, mergeMap } from 'rxjs/operators';
 
const DEFAULT_CONSTANTS = ['SET', 'RESET'];
 
export interface CreateStateRxOpts<E, Api, State> {
  name?: string;
  autoRun?: boolean;
  effects?: (srx: Api) => E;
  reducer?: (state: State, action: AnyAction) => State;
}
 
export interface CreateStateRxApi<S> {
  name: string;
  state$: BehaviorSubject<S>;
  action$: Observable<AnyAction<any>>;
  get: () => S;
  set: (data: S | ((val: S) => S)) => { type: string; data: S };
  reset: () => { type: string };
  dispatch: <A extends AnyAction>(action: A) => A;
  _dispatchers$: Subject<Subject<AnyAction<any>>>;
}
 
export interface CloneApi<State, Api, Effects> {
  clone: (initialState?: State) => Api & Effects;
}
 
type CreateReducer<T, S> = (params: { constant: Constants }) => Reducer<S>;
 
type CreateActions<T, S, A> = (params: {
  constant: Constants;
  get: () => S;
  dispatch: Dispatch;
}) => A;
 
type CreateSelectors<T, S, R> = (state$: BehaviorSubject<S>) => R;
 
const createBaseActions = <T>({
  constant,
  get
}: {
  constant: Constants;
  get: () => T;
}) => {
  const dispatch$ = new Subject<AnyAction<any>>();
  const _dispatchers$ = new Subject<Subject<AnyAction<any>>>();
 
  const action$ = merge<AnyAction<any>>(
    dispatch$,
    _dispatchers$.pipe(mergeMap((obs$) => obs$))
  );
 
  const dispatch = wrapDispatchSubject(dispatch$);
 
  return {
    action$,
    set: (data: T | ((val: T) => T)) => {
      // @ts-ignore
      data = typeof data === 'function' ? data(get()) : data;
      return dispatch({ type: constant.SET, data });
    },
    reset: () => dispatch({ type: constant.RESET }),
    dispatch,
    _dispatchers$
  };
};
 
const createBaseReducer = <S>({
  initialState,
  constant,
  reducer,
  userReducer
}: {
  initialState: S;
  constant: Constants;
  reducer: Reducer;
  userReducer: Reducer;
}) => (state: any, action: AnyAction): S => {
  const type = action.type.split('/', 2).join('/');
 
  switch (type) {
    case constant.SET:
      return action.data;
    case constant.RESET:
      return initialState;
    default:
      const res = reducer(state, action);
      // if the result is the same as our initial state
      // pass it on to the user reducer
      return res === state ? userReducer(state, action) : res;
  }
};
 
export const createStateRx = <
  T,
  State,
  Effects,
  ConstantsArray extends string[],
  Actions extends {},
  Selectors extends {},
  Api extends CreateStateRxApi<State>
>(
  initialState: State,
  options: CreateStateRxOpts<Effects, Api, State>,
  overrides: {
    state$: BehaviorSubject<State>;
    constants: ConstantsArray;
    createReducer: CreateReducer<T, State>;
    createActions: CreateActions<T, State, Actions>;
    createSelectors?: CreateSelectors<T, State, Selectors>;
  }
) => {
  const {
    name = genRandomString(),
    autoRun = true,
    reducer: userReducer = (state) => state
  } = options;
 
  const {
    state$,
    constants,
    createReducer,
    createActions,
    createSelectors
  } = overrides;
 
  const constant = createConstants(name, [...DEFAULT_CONSTANTS, ...constants]);
 
  const get = () => state$.getValue();
 
  const { action$, dispatch, ...baseActions } = createBaseActions({
    constant,
    get
  });
 
  const { ...actions } = createActions({
    constant,
    get,
    dispatch
  });
 
  const selectors = createSelectors?.(state$);
 
  const reducer = createBaseReducer({
    constant,
    initialState,
    reducer: createReducer({
      constant
    }),
    userReducer
  });
 
  const clone = (newInitialState: State = get()) =>
    createStateRx(newInitialState, options, {
      ...overrides,
      state$: new BehaviorSubject<State>(newInitialState)
    });
 
  const _reducer$ = action$.pipe(
    map((action) => reducer(state$.getValue(), action)),
    distinctUntilChanged()
  );
 
  const run = () => _reducer$.subscribe(state$);
 
  const api = ({
    ...actions,
    ...selectors,
    ...baseActions,
    name,
    state$,
    action$,
    constant,
    run,
    get,
    clone,
    dispatch,
    _reducer$
  } as unknown) as Api & CloneApi<State, Api, Effects>;
 
  const effects = options.effects?.(api) as Effects;
 
  autoRun && run();
 
  return { ...api, ...effects };
};