UNPKG

contiago-toolbar

Version:

One of the options for outputting content from contiago xml-server

62 lines (56 loc) 1.93 kB
import 'whatwg-fetch'; import config from '../../config.json'; /** * Parses the JSON returned by a network request * * @param {object} response A response from a network request * * @return {object} The parsed JSON from the request */ function parseJSON(response) { if (response.status === 204 || response.status === 205) { return null; } return response.json(); } /** * Checks if a network request came back fine, and throws an error if not * * @param {object} response A response from a network request * * @return {object|undefined} Returns either the response, or throws an error */ function checkStatus(response) { if (response.status >= 400) { throw response; } return response; } /** * Requests a URL, returning a promise * * @param {string} url The URL we want to request * @param {object} [options] The options we want to pass to "fetch" * * @return {object} The response data */ export default function request(url, options = {}) { const resultUrl = options.getParamsObject && !options.method ? `${url}?${Object.keys(options.getParamsObject) .filter((paramName) => options.getParamsObject[paramName] !== undefined && options.getParamsObject[paramName] != null) .map((paramName) => `${paramName}=${options.getParamsObject[paramName]}`).join('&')}` : url; const host = localStorage.getItem(config['toolbar.sandbox.attribute.name']) ? config.sandboxXmlContentServerHost : config.xmlContentServerHost; const customOptions = { ...options, headers: { 'Content-Type': 'application/json', [`${config['toolbar.access.token.header.name']}`]: localStorage.getItem(`${config['toolbar.access.token.header.name']}`), Accept: '*/*', ...(options.headers || {}), }, }; return fetch(`${host}${resultUrl}`, customOptions) .then(parseJSON) .then(checkStatus); }