All files / src/adapter ApiAdapter.js

86.36% Statements 19/22
83.33% Branches 10/12
100% Functions 6/6
86.36% Lines 19/22
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        8x 8x               3x 3x 3x 3x 3x 8x               8x 8x             9x       8x 8x 8x 3x 3x   8x 8x 8x              
import _ from 'lodash'
import queryString from 'query-string'
 
function handleStatus(response) {
  Eif (response.status >= 200 && response.status < 300) {
    return response
  } else {
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
}
 
const rxOne = /^[\],:{}\s]*$/;
const rxTwo = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
const rxThree = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
const rxFour = /(?:^|:|,)(?:\s*\[)+/g;
const isJSON = (input) => (
  input.length && rxOne.test(
    input.replace(rxTwo, '@')
      .replace(rxThree, ']')
      .replace(rxFour, '')
  )
);
 
function parse(response) {
  return response.text().then(function (text) {
    return isJSON(text) ? JSON.parse(text) : {}
  })
}
 
//TODO: Add custom fetch support with subclassing
export default class APIAdapter {
  constructor(config) {
    this.globalOptions = config.globalOptions
  }
 
  fetch(path, method, fetchOptions, handler, errorHandler) {
    const finalOptions = _.merge({}, this.globalOptions, fetchOptions)
    const { params } = finalOptions
    if (params && !_.isEmpty(params)) {
      path = `${path}?${queryString.stringify(params)}`
      delete fetchOptions.params
    }
    console.log('calling with options ', finalOptions, fetchOptions)
    finalOptions.method = method
    return fetch(path, finalOptions)
      .then(handleStatus)
      .then(parse)
      .then(handler)
      .catch(errorHandler)
  }
}