import getMoovEnv from './get-moov-env'; import getApiPath from './get-api-path'; /* * A convenient wrapper for XMLHttpRequests */ type FakeFetchHeader = [string, string]; export type AuthedFetchType = (url: string, opts?: FakeFetchOptions) => Promise; type CreateAuthedFetchType = (accessToken: string) => AuthedFetchType; interface FakeFetchOptions { headers?: Array; method?: "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; body?: object | string | FormData; file?: boolean; } const moovEnv = getMoovEnv(); const basePath = getApiPath(moovEnv); export const parseError = (xhr: XMLHttpRequest) => { if (xhr.response) { try { return JSON.parse(xhr.response).error; } catch { return "API request error"; } } return "API request error"; }; const fakeFetch = (url: string, opts: FakeFetchOptions = {}) => { const xhr = new XMLHttpRequest(); // Default to 'GET' if method isn't given const method = opts.method || "GET"; return new Promise(function (resolve, reject) { xhr.onreadystatechange = function () { // Don't do anything until request has completed if (xhr.readyState !== 4) { return; } // Resolve when request is valid, or reject otherwise if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr.response); } else { reject({ statusCode: xhr.status, error: parseError(xhr) }); } }; // Kick things off xhr.open(method, url, true); if (moovEnv !== "mock") xhr.withCredentials = true; // Set headers if applicable if (opts.headers && opts.headers.length > 0) { opts.headers.forEach((headerArray) => { xhr.setRequestHeader(...headerArray); }); } // handle multipart upload if (opts.file) { xhr.send(opts.body as FormData); } else if (opts.body) { // Add a header if we're sending a body xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(JSON.stringify(opts.body)); } else { xhr.send(); } }); }; // Add base path to API requests export const plainFetch = (url: string, opts: FakeFetchOptions) => fakeFetch(basePath + url, opts) .then((res: any) => { try { return JSON.parse(res); } catch { return res; } }); // Add auth header with token to API requests const createAuthedFetch: CreateAuthedFetchType = (accessToken: string) => (url: string, opts: FakeFetchOptions = {}) => { const optsWithAuthHeader: FakeFetchOptions = { ...opts, headers: [...(opts.headers ? opts.headers : []), ["Authorization", "Bearer " + accessToken]], }; return plainFetch(url, optsWithAuthHeader); }; export default createAuthedFetch as CreateAuthedFetchType;