Skip to content

Instantly share code, notes, and snippets.

@terakilobyte
Created October 20, 2018 15:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save terakilobyte/b19d995e424dc2d16f00b3c9b3046167 to your computer and use it in GitHub Desktop.
Save terakilobyte/b19d995e424dc2d16f00b3c9b3046167 to your computer and use it in GitHub Desktop.
request
/**
* 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