All files / src fetchResource.js

50% Statements 9/18
30% Branches 3/10
55.56% Functions 5/9
50% Lines 9/18
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                    4x       4x 3x         2x 2x                         1x     1x       1x                     1x                                                      
import "fetch-everywhere";
import * as types from "./constants/ActionTypes";
 
/**
 * Will fetch a resources from a remote endpoint and dispatch an action when
 * successfully returned.
 *
 * @return {Promise}
 */
export default ({ endpoint, dispatch, successAction }) =>
  fetch(new Request(endpoint, { redirect: "manual" }), {
    credentials: "include",
  })
    .then(response => {
      if (response.status === 200) {
        return response
          .json()
          .then(payload => {
            // We don't want any errors thrown during the dispatch to be caught
            // by our promise chain. So run the try/catch here.
            try {
              dispatch({
                type: successAction,
                meta: { endpoint, status: response.status },
                payload,
                response,
              });
            } catch (e) {
              if (process.env.NODE_ENV !== "production") {
                // eslint-disable-next-line no-console
                console.warn(e);
              }
            }
          })
          .catch(() => dispatch({ type: types.BAD_JSON, meta: { endpoint } }));
      }
 
      Iif (typeof window === "undefined") {
        throw response;
      }
 
      return response
        .json()
        .then(payload =>
          dispatch({
            type: types.RESOURCE_FAIL,
            meta: { endpoint, status: response.status },
            payload,
            response,
          }),
        )
        .catch(() =>
          dispatch({
            type: types.RESOURCE_FAIL,
            meta: { endpoint, status: response.status },
            payload: {},
            response,
          }),
        );
    })
    // None of this is tested as of yet. This is experimental and most likely
    // will not exist in this form at the end of the day.
    .catch(response => {
      if (response.status === 301 || response.status === 302) {
        return response
          .json()
          .then(redirect => ({
            statusCode: response.status,
            url: redirect.location,
          }))
          .catch(() => ({ statusCode: response.status, url: "/" }));
      }
 
      return dispatch({
        type: "@@horseman/FETCH_RESOURCE_FAIL",
        meta: { endpoint, status: response.status },
        payload: {},
      });
    });