All files / src/domain/Api index.js

96.23% Statements 51/53
84.62% Branches 22/26
92.31% Functions 12/13
98.04% Lines 50/51
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                  12x 12x 12x   12x           17x   17x 17x 17x 17x 17x 17x 17x       12x 8x 8x   8x 8x 8x     8x 8x 5x   4x   1x       8x 8x 8x   8x       6x 6x     2x 2x             8x       8x                             8x   8x 8x   1x           8x 6x     2x 2x 2x   2x 1x   1x 1x 1x       2x                 12x 12x      
import invariant from 'invariant';
import isomorphicFetch from 'isomorphic-fetch';
import is from 'is_js';
import camelCase from 'lodash.camelcase';
import log from 'domain/log';
import Store from 'domain/Store';
import Config from 'domain/Config';
 
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Simple_requests
const CORS_SIMPLE_METHODS = ['GET', 'HEAD'];  // omit POST, we must send a `Content-Type`
const SECURE_URL_REGEXP = /^(https:)?\/\//;
const IS_BEARER_TOKEN_IN_URLS_ENABLED = !! Config.get('includeBearerTokenInApiGetUrls');
 
export const buildUrl = (path) => Config.get('apiBase') + path;
 
class FetchTimedOutError extends Error { }
 
export class ApiError extends Error {
  constructor(response = {}, message) {
    super(message || response.statusText);
    // https://fetch.spec.whatwg.org/#responses
    this.ok = response.ok;
    this.url = response.url;
    this.type = response.type;
    this.status = response.status;
    this.statusText = response.statusText;
    this.headers = response.headers;
    this.body = response.body;
  }
}
 
export const fetch = (url, options = {}) => {
  invariant(is.string(url), 'url must be a string');
  invariant(is.object(options), 'options must be a plain object');
 
  const user = Store.get().getState().get('singleSignOn').get('user') || {};
  const accessToken = user.get('access_token');
  const finalOptions = Object.assign({}, options, getDefaultFetchOpts(options, accessToken));
 
  // https://m.alphasights.com/killing-cors-preflight-requests-on-a-react-spa-1f9b04aa5730#4bdf
  let finalUrl = url;
  if (IS_BEARER_TOKEN_IN_URLS_ENABLED) {
    if (SECURE_URL_REGEXP.test(url)) {
      // eslint-disable-next-line prefer-template
      finalUrl = url + (url.includes('?') ? '&' : '?') + `bearer_token=${accessToken}`;
    } else {
      log.warn('Refusing to append `bearer_token` to a non-secure URL', url);
    }
  }
 
  return new Promise((resolve, reject) => {
    const onTimeout = () => reject(new FetchTimedOutError(`Call to ${url} has taken too long!`));
    const timeout = setTimeout(onTimeout, Config.get('fetchTimeout'));
 
    isomorphicFetch(finalUrl, finalOptions)
      .then(checkResponseStatus)
      .then(parseResponse)
      .then((response) => {
        clearTimeout(timeout);
        resolve(response);
      })
      .catch((error) => {
        clearTimeout(timeout);
        reject(error);
      });
  });
};
 
function getDefaultFetchOpts(options, token) {
  const isCorsSimpleMethod =
      is.empty(options) ||
      is.falsy(options.method) ||
      (is.string(options.method) &&
        CORS_SIMPLE_METHODS.includes(options.method.toUpperCase()));
  return {
    headers: Object.assign(
      { Accept: 'application/json; charset=utf-8' },
      ! IS_BEARER_TOKEN_IN_URLS_ENABLED ? {
        Authorization: `Bearer ${token}`,
      } : {},
      ! isCorsSimpleMethod ? {
        'Content-Type': 'application/json',
      } : {},
      is.not.object(options) ? undefined : options.headers
    ),
  };
}
 
function parseResponse(rawResponse) {
  return rawResponse.text()
      .then((response) => {
        try {
          return JSON.parse(response);
        } catch (e) {
          return response;
        }
      });
}
 
function checkResponseStatus(response) {
  if (response.ok) {
    return response;
  }
 
  const error = new ApiError(response);
  try {
    return parseResponse(response)
        .then((apiResponse) => {
          if (is.not.object(apiResponse)) {
            error.response = apiResponse;
          } else {
            error.response = {};
            Object.keys(apiResponse).forEach((key) => {
              error.response[camelCase(key)] = apiResponse[key];
            });
          }
 
          throw error;
        });
  } catch (e) {
    throw error;
  }
}
 
class Api { }
 
Api.fetch = fetch;
Api.buildUrl = buildUrl;
 
export default Api;