All files / src middleware.js

100% Statements 22/22
87.5% Branches 7/8
100% Functions 7/7
100% Lines 20/20
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                            2x 2x 17x   3x 15x 15x   15x 45x 28x 28x     17x 17x   17x 3x 3x     14x   14x   8x 8x       5x                
import fetch from 'redux-api-call-adapter-fetch';
import parseJSON from 'redux-api-call-adapter-json';
import dedupe from 'redux-api-call-adapter-dedupe';
 
import {
  makeFailureAction,
  makeStartAction,
  makeStartErrorAction,
  makeSuccessAction,
} from './actions';
import applyFunctions from './utils/applyFunctions';
import composeAdapters from './composeAdapters.js';
import { CALL_API } from './constants';
 
const defaultAdapter = composeAdapters(parseJSON, dedupe, fetch);
const isValid = api =>
  typeof api.name === 'string' && typeof api.endpoint === 'string';
 
export const createAPIMiddleware = adapter => ({ dispatch, getState }) => {
  const finalAdapter = adapter(getState);
  const resolveState = applyFunctions(getState);
 
  return next => action => {
    if (!action[CALL_API]) {
      next(action);
      return;
    }
 
    const rawRequest = action[CALL_API];
    const request = resolveState(rawRequest);
 
    if (!isValid(request)) {
      dispatch(makeStartErrorAction(request)());
      return;
    }
 
    dispatch(makeStartAction(request)());
 
    finalAdapter(request).then(
      response => {
        Eif (response) {
          dispatch(makeSuccessAction(request)(response.payload, response.meta));
        }
      },
      failure => {
        dispatch(makeFailureAction(request)(failure.payload, failure.meta));
      }
    );
  };
};
 
// middleware
export default createAPIMiddleware(defaultAdapter);