79 lines
1.8 KiB
JavaScript
Raw Normal View History

2017-01-17 13:40:59 +01:00
import 'whatwg-fetch';
/**
* 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) {
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
*
2017-04-11 11:34:59 +02:00
* @return {object|undefined} Returns either the response, or throws an error
2017-01-17 13:40:59 +01:00
*/
function checkStatus(response) {
2017-04-11 11:34:59 +02:00
if (response.status >= 200 && response.status < 300) {
return response;
}
return parseJSON(response)
.then((responseFormatted) => {
const error = new Error(response.statusText);
error.response = response;
error.response.payload = responseFormatted;
throw error;
});
}
/**
* Format query params
*
* @param params
* @returns {string}
*/
function formatQueryParams(params) {
return Object.keys(params)
.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`)
.join('&');
2017-01-17 13:40:59 +01:00
}
/**
* 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"
*
2017-04-11 11:34:59 +02:00
* @return {object} The response data
2017-01-17 13:40:59 +01:00
*/
export default function request(url, options) {
2017-04-11 11:34:59 +02:00
const optionsObj = options || {};
// Set headers
optionsObj.headers = {
2017-01-17 13:40:59 +01:00
'Content-Type': 'application/json',
};
2017-04-11 11:34:59 +02:00
// Add parameters to url
let urlFormatted = url;
if (optionsObj && optionsObj.params) {
const params = formatQueryParams(optionsObj.params);
urlFormatted = `${url}?${params}`;
}
// Stringify body object
if (optionsObj && optionsObj.body) {
optionsObj.body = JSON.stringify(optionsObj.body);
}
return fetch(urlFormatted, optionsObj)
2017-01-17 13:40:59 +01:00
.then(checkStatus)
2017-04-11 11:34:59 +02:00
.then(parseJSON);
2017-01-17 13:40:59 +01:00
}