All files / src fetch.js

88.46% Statements 115/130
84.21% Branches 48/57
78.13% Functions 25/32
82.35% Lines 28/34
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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 1756x                                       6x                                       6x                                                               6x                                       48x       8x   32x   2x                           8x           8x 8x             8x 1x 7x 1x   6x                     8x 8x                         8x 8x 4x 4x 4x       8x 1x 7x 1x   6x      
/* globals fetch */
 
import isObject from 'lodash.isobject'
import {createAction} from 'redux-actions'
if (typeof (fetch) === 'undefined') {
  require('isomorphic-fetch')
}
 
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) {
  const headers = {
    ...createAuthorizationHeader(state),
    ...createContentHeader(options.body),
    ...(options.headers || {})
  }
 
  const filteredHeaders = {}
 
  // allow removing generated headers by specifiying { header: null } in options.headers
  // do this in two steps because otherwise we're modifying the object as we're iterating over it
  Object.keys(headers)
    .filter(key => headers[key] !== null && headers[key] !== undefined)
    .forEach(key => { filteredHeaders[key] = headers[key] })
 
  return fetch(url, {
    ...options,
    body: serialize(options.body),
    headers: filteredHeaders
  })
    .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 [
    ...fetches.map(({options, url}) => incrementFetches({options, url})),
    Promise.all(fetches.map((fetch) => runFetch(fetch, state)))E
      .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
  }
}