All files / src middleware.js

100% Statements 25/25
100% Branches 10/10
100% Functions 6/6
100% Lines 23/23
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                          2x     17x 1x         16x 2x         14x       14x 14x 8x   5x         3x 15x 15x   15x   29x 17x   17x 17x 3x 3x       26x   26x   14x              
import dedupe from 'redux-api-call-adapter-dedupe';
import fetch from 'redux-api-call-adapter-fetch';
import parseJSON from 'redux-api-call-adapter-json';
 
import { ACTION_FETCH_START } from './constants';
import {
  makeFailureAction,
  makeStartErrorAction,
  makeSuccessAction,
} from './actions';
import applyFunctions from './utils/applyFunctions';
import composeAdapters from './composeAdapters.js';
 
const defaultAdapter = composeAdapters(parseJSON, dedupe, fetch);
 
function validate(request) {
  if (typeof request.name !== 'string') {
    return makeStartErrorAction({
      ...request,
      error: 'no api name is specified',
    });
  }
  if (typeof request.endpoint !== 'string') {
    return makeStartErrorAction({
      ...request,
      error: 'no api endpoint is specified',
    });
  }
  return false;
}
 
async function tryRequest(request, adapter) {
  try {
    const response = await adapter(request);
    return makeSuccessAction(request, response);
  } catch (failure) {
    return makeFailureAction(request, failure);
  }
}
 
export function createAPIMiddleware(adapter) {
  return ({ dispatch, getState }) => {
    const finalAdapter = adapter(getState);
    const resolveState = applyFunctions(getState);
 
    return next => async action => {
      let request;
      if (action.type === ACTION_FETCH_START) {
        request = resolveState(action.payload);
 
        const errorAction = validate(request);
        if (errorAction) {
          next(errorAction);
          return;
        }
      }
 
      next(action);
 
      if (action.type !== ACTION_FETCH_START) return;
 
      dispatch(await tryRequest(request, finalAdapter));
    };
  };
}
 
// middleware
export default createAPIMiddleware(defaultAdapter);