2018-01-25 22:37:59 +01:00
|
|
|
/**
|
|
|
|
* 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();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2018-02-13 21:19:57 +01:00
|
|
|
* Parses the status returned by a network request
|
2018-01-25 22:37:59 +01:00
|
|
|
*
|
|
|
|
* @param {object} response A response from a network request
|
2018-02-13 21:19:57 +01:00
|
|
|
* @param {object} response The parsed JSON from the network request
|
2018-01-25 22:37:59 +01:00
|
|
|
*
|
2018-02-13 21:19:57 +01:00
|
|
|
* @return {object | undefined} Returns object with status and statusText, or undefined
|
2018-01-25 22:37:59 +01:00
|
|
|
*/
|
2018-02-13 21:19:57 +01:00
|
|
|
function checkStatus (response, jsonResponse) {
|
2018-01-25 22:37:59 +01:00
|
|
|
if (response.status >= 200 && response.status < 300) {
|
2018-02-13 21:19:57 +01:00
|
|
|
return jsonResponse;
|
2018-01-25 22:37:59 +01:00
|
|
|
}
|
2018-02-13 21:19:57 +01:00
|
|
|
const error = new Error(jsonResponse.message);
|
2018-01-25 22:37:59 +01:00
|
|
|
error.response = response;
|
|
|
|
throw error;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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
|
|
|
|
*/
|
2018-02-13 21:19:57 +01:00
|
|
|
|
2018-01-25 22:37:59 +01:00
|
|
|
export default function request (url, options) {
|
|
|
|
return fetch(url, options)
|
2018-02-13 21:19:57 +01:00
|
|
|
.then(response => {
|
|
|
|
return Promise.all([response, parseJSON(response)]);
|
|
|
|
})
|
|
|
|
.then(([response, jsonResponse]) => {
|
|
|
|
return checkStatus(response, jsonResponse);
|
|
|
|
});
|
2018-01-25 22:37:59 +01:00
|
|
|
}
|