All files / src fetch.js

88.12% Statements 89/101
75.51% Branches 37/49
76.92% Functions 20/26
82.93% Lines 34/41
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 1416x                               42x 4x 31x 4x 27x 1x   26x     6x                           6x 6x 6x                     24x 6x 6x 6x               4x 4x     4x                           1x 1x   2x 1x               6x           6x 6x             6x                       6x 6x                         6x 6x 2x 2x 2x    
import fetch from 'isomorphic-fetch'
import isObject from 'lodash.isobject'
import {createAction} from 'redux-actions'
 
export const INCREMENT_FETCH = 'increment outstanding fetches'
export const DECREMENT_FETCH = 'decrement outstanding fetches'
export const FETCH = 'fetch'
export const FETCH_MULTIPLE = 'fetch multiple'
export const FETCH_ERROR = 'fetch error'
 
export const incrementFetches = createAction(INCREMENT_FETCH)
export const decrementFetches = createAction(DECREMENT_FETCH)
export const fetchAction = createAction(FETCH)
export const fetchMultiple = createAction(FETCH_MULTIPLE)
export const fetchError = createAction(FETCH_ERROR)
 
export function middleware (store) {
  return (next) => (action) => {
    if (action.type === FETCH) {
      return store.dispatch(runFetchAction(action.payload, store.getState()))
    } else if (action.type === FETCH_MULTIPLE) {
      return store.dispatch(runFetchMultiple(action.payload, store.getState()))
    } else {
      return next(action)
    }
  }
}
 
export default fetchAction
 
/**
 * Calls fetch, adds Auth and Content header if needed. Automatically parses content based on type.
 *
 * @returns Promise
 */
 
function runFetch ({
  options = {},
  retry = false,
  url
}, state) {
  const isJSON = isObject(options.body)
  return fetch(url, {
    ...options,
    body: isJSON ? JSON.stringify(options.body) : options.body,
    headers: {
      ...createAuthorizationHeader(state),
      ...createContentHeader(isJSON),
      ...(options.headers || {})
    }
  })
    .then(checkStatus)
    .then(createResponse)
    .then(async (response) =>
      (retry && await retry(response))E
        ? runFetch({options, retry, url}, state)
        : response)
}
 
function runFetchAction ({
  next,
  options = {},
  retry = false,
  url
}, state) {
  return [
    incrementFetches(),
    runFetch({options, retry, url}, state)
      .then((response) => [decrementFetches(), next(null, response)])
      .catch((error) =>
        createErrorResponse(error)
          .then((response) => [decrementFetches(), fetchError(response), next(error, response)]))
  ]
}
 
/**
 * @returns Promise
 */
 
function runFetchMultiple ({
  fetches,
  next
}, state) {
  return [
    incrementFetches(),
    Promise.all(fetches.map((fetch) => runFetch(fetch, state)))
      .then((responses) => [decrementFetches(), next(null, responses)])
      .catch((error) =>
        createErrorResponse(error)
          .then((response) => [decrementFetches(), fetchError(response), next(error, response)]))
  ]
}
 
function createAuthorizationHeader (state) {
  return state.user && state.user.idToken
    ? {Authorization: `bearer ${state.user.idToken}`}
    : {}
}
 
function checkStatus (res) {
  Eif (res.status >= 200 && res.status < 300) {
    return res
  } else {
    throw res
  }
}
 
function createContentHeader (isJSON) {
  return isJSON
    ? {'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8'}
    : {}
}
 
function createErrorResponse (res) {
  return res.headers
    ? createResponse(res)
    : Promise.resolve(res)
}
 
function createResponse (res) {
  return deserialize(res)
    .then((value) => ({
      url: res.url,
      status: res.status,
      statusText: res.statusText,
      headers: res.headers,
      value
    }))
    .catch((err) => ({
      value: err
    }))
}
 
function deserialize (res) {
  const header = `${res.headers.get('Content-Type')} ${res.headers.get('Content')}`
  if (header.indexOf('application/json') > -1) return res.json()
  Iif (header.indexOf('application/ld+json') > -1) return res.json()
  Iif (header.indexOf('application/octet-stream') > -1) return res.arrayBuffer()
  return res.text()
}