All files / src makeFetchAction.js

100% Statements 19/19
100% Branches 6/6
100% Functions 5/5
100% Lines 16/16
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                1x               4x 1x   3x 1x   2x       1x                 1x               4x               1x 1x 1x 1x 1x 1x   1x                        
import {
  ACTION_FETCH_START,
  ACTION_RESET_LOCAL,
  ACTION_UPDATE_LOCAL,
  REDUCER_PATH,
} from './constants';
import get from './utils/get';
 
const normalizeResetData = (data = [
  'lastRequest',
  'isFetching',
  'isInvalidated',
  'lastResponse',
  'data',
  'error',
]) => {
  if (typeof data === 'string') {
    return [data];
  }
  if (!Array.isArray(data)) {
    throw new Error('You are using resetter wrong, the params should be string, array or undefined');
  }
  return data;
}
 
export default (apiName, apiConfigFn, selectorDescriptor = {}) => {
  const actionCreator = (...params) => ({
    type: ACTION_FETCH_START,
    payload: {
      ...apiConfigFn(...params),
      name: apiName,
      requestedAt: Date.now(),
    },
  });
 
  const updater = data => ({
    type: ACTION_UPDATE_LOCAL,
    payload: {
      name: apiName,
      data,
    },
  });
 
  const resetter = data => ({
    type: ACTION_RESET_LOCAL,
    payload: {
      name: apiName,
      data: normalizeResetData(data)
    },
  });
 
  const isFetchingSelector = get([REDUCER_PATH, apiName, 'isFetching'], false);
  const isInvalidatedSelector = get([REDUCER_PATH, apiName, 'isInvalidated'], false);
  const dataSelector = get([REDUCER_PATH, apiName, 'data'], null);
  const headersSelector = get([REDUCER_PATH, apiName, 'headers'], null);
  const errorSelector = get([REDUCER_PATH, apiName, 'error'], null);
  const lastResponseSelector = get([REDUCER_PATH, apiName, 'lastResponse'], null);
 
  return {
    actionCreator,
    updater,
    isFetchingSelector,
    isInvalidatedSelector,
    dataSelector,
    headersSelector,
    errorSelector,
    lastResponseSelector,
    resetter,
  };
};