Created
October 20, 2018 15:39
-
-
Save terakilobyte/b19d995e424dc2d16f00b3c9b3046167 to your computer and use it in GitHub Desktop.
request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Parses the JSON returned by a network request | |
* | |
* @param {object} response A response from a network request | |
* | |
* @return {object} The parsed JSON, status from the response | |
*/ | |
function parseJSON(response) { | |
return new Promise(resolve => | |
response.json().then(json => | |
resolve({ | |
status: response.status, | |
ok: response.ok, | |
json | |
}) | |
) | |
) | |
} | |
/** | |
* 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 {Promise} The request promise | |
*/ | |
export default function request(url, options) { | |
return new Promise((resolve, reject) => { | |
fetch(url, options) | |
.then(parseJSON) | |
.then(response => { | |
if (response.ok) { | |
return resolve(response.json) | |
} | |
// extract the error from the server's json | |
return reject(response.json) | |
}) | |
.catch(error => | |
reject({ | |
error | |
}) | |
) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment