60 lines
1.5 KiB
JavaScript
Raw Normal View History

2016-09-25 21:54:59 +02: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
*
2016-10-04 17:49:40 +02:00
* @return {Promise} Returns either the response, or throws an error
2016-09-25 21:54:59 +02:00
*/
function checkStatus(response) {
2016-11-18 16:18:29 +01:00
return new Promise((resolve) => {
2016-10-04 16:31:52 +02:00
if (response.status >= 200 && response.status < 300) {
return resolve(response);
}
2016-09-25 21:54:59 +02:00
2016-10-04 17:49:40 +02:00
return parseJSON(response)
2016-11-18 16:18:29 +01:00
.then((data) => {
2016-10-04 16:31:52 +02:00
const error = new Error(data.message || response.statusText);
error.data = data;
error.response = response;
throw error;
});
});
2016-09-25 21:54:59 +02: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"
*
* @return {object} An object containing either "data" or "err"
*/
export default function request(url, options) {
2016-09-26 17:28:40 +02:00
// Default headers
2016-10-04 17:49:40 +02:00
const params = options || { };
const defaultHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
2016-09-26 17:28:40 +02:00
};
2016-10-04 17:49:40 +02:00
params.headers = params && params.headers ? params.headers : defaultHeaders;
2016-09-26 17:28:40 +02:00
2016-10-04 17:49:40 +02:00
return fetch(url, params)
2016-09-25 21:54:59 +02:00
.then(checkStatus)
.then(parseJSON)
.then((data) => ({ data }))
.catch((err) => ({ err }));
}