All files / src/redux reducer.ts

17.5% Statements 7/40
15.79% Branches 3/19
100% Functions 1/1
17.14% Lines 6/35

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                              1x     1x       4x   4x       4x   4x                                                                                                    
import { cloneDeep } from "lodash";
import {
  errors,
  loading,
  progress,
  COMPLETE,
  FAILURE,
  PROGRESS,
  RESET,
  START,
  meta
} from "./utils";
import { Action, StatusState } from "./types";
import { LOGOUT_ACTION } from "../apps/authentication/redux/actionTypes";
 
const initialState: StatusState = {};
 
// todo improve these action types args
const loadingAndErroredReducer = (
  state: StatusState = initialState,
  action: Action
) => {
  const { type, payload, actionIndex, meta: actionMeta } = action;
 
  Iif (type === LOGOUT_ACTION) {
    return Object.assign({}, initialState);
  }
 
  const matches = /(.*)_(START|PROGRESS|FAILURE|COMPLETE|RESET)/.exec(type);
 
  Eif (!matches) return state;
 
  const [, actionName, requestState] = matches;
  const loadingName = loading(actionName);
  const progressName = progress(actionName);
  const errorName = errors(actionName);
  const metaName = meta(actionName);
 
  const newState = cloneDeep(state);
 
  switch (requestState) {
    case RESET: {
      newState[loadingName] = [];
      newState[progressName] = [];
      newState[errorName] = [];
      newState[metaName] = [];
 
      return newState;
    }
    case START: {
      if (!newState[loadingName]) newState[loadingName] = [];
      if (!newState[progressName]) newState[progressName] = [];
      if (!newState[errorName]) newState[errorName] = [];
      if (!newState[metaName]) newState[metaName] = [];
 
      newState[loadingName][actionIndex] = true;
      newState[progressName][actionIndex] = undefined;
      newState[errorName][actionIndex] = undefined;
      newState[metaName][actionIndex] = actionMeta;
 
      return newState;
    }
    case COMPLETE: {
      newState[loadingName][actionIndex] = false;
      return newState;
    }
    case PROGRESS: {
      newState[progressName][actionIndex] = payload;
      return newState;
    }
    case FAILURE: {
      newState[errorName][actionIndex] = payload;
      return newState;
    }
    default:
      return state;
  }
};
 
export default loadingAndErroredReducer;