All files / src fetch.js

87.8% Statements 108/123
83.02% Branches 44/53
76.67% Functions 23/30
82.86% Lines 29/35
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 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 1616x                               6x                                       6x                                           6x                                       48x       32x   2x 1x 2x                           8x           8x 8x             8x 1x 7x 1x   6x                     8x 8x                         8x 8x 4x 4x 4x       8x 1x 7x 1x   6x      
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
 */
 
export function runFetch ({
  options = {},
  retry = false,
  url
}, state) {
  return fetch(url, {
    ...options,
    body: serialize(options.body),
    headers: {
      ...createAuthorizationHeader(state),
      ...createContentHeader(options.body),
      ...(options.headers || {})
    }
  })
    .then(checkStatus)
    .then(createResponse)
    .then(async (response) =>
      (retry && await retry(response))
        ? runFetch({options, retry, url}, state)
        : response)
}
 
export function runFetchAction ({
  next,
  options = {},
  retry = false,
  url
}, state) {
  return [
    incrementFetches({options, url}),
    runFetch({options, retry, url}, state)
      .then((response) => [decrementFetches({options, url}), next(null, response)])
      .catch((error) =>
        createErrorResponse(error)
          .then((response) => [decrementFetches({options, url}), fetchError(response), next(error, response)]))
  ]
}
 
/**
 * @returns Promise
 */
 
export function runFetchMultiple ({
  fetches,
  next
}, state) {
  return [E
    ...fetches.map(({options, url}) => incrementFetches({options, url})),
    Promise.all(fetches.map((fetch) => runFetch(fetch, state)))
      .then((responses) => [
        ...fetches.map(({options, url}) => decrementFetches({options, url})),
        next(null, responses)
      ])
      .catch((error) =>
        createErrorResponse(error)
          .then((response) => [
            ...fetches.map(({options, url}) => decrementFetches({options, url})),
            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 (body) {
  if (body instanceof window.FormData) {
    return {}
  } else if (isObject(body)) {
    return {'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8'}
  } else {
    return {}
  }
}
 
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()
}
 
function serialize (body) {
  if (body instanceof window.FormData) {
    return body
  } else if (isObject(body)) {
    return JSON.stringify(body)
  } else {
    return body
  }
}