ES6 fetch syntactic sugar: handling common fetch usage with json content type, same headers, and stringified body
/* | |
fetch is awesome, there's no question about it. | |
But aren't you tired of: | |
- Writing your `res => res.json()` handler | |
- Having to stringify your body | |
- Signin your request with the same headers (```{'Content-Type': json, Authorization: 'JWT ...'}```) | |
- Inconsistently handling the response status code and not reject promise when relevant. | |
Usage: | |
request('http://yourawesome.api.com').then(console.log).catch(console.error); | |
request('http://yourawesome.api.com', { | |
method: 'PUT', | |
body: { coworkingAt: 'fishburners' }, | |
}) | |
.then(console.log) | |
.catch(console.error); | |
*/ | |
const defaultHeaders = { 'Content-Type': 'application/json' }; | |
const RESOLVE_STATUS_CODES = [200]; | |
const request = (url, options = {}) => { | |
const params = Object.assign({}, options, { | |
headers: Object.assign(defaultHeaders, options.headers || {}) | |
}); | |
if (options.body && typeof options.body !== 'string') { | |
params.body = JSON.stringify(options.body); | |
} | |
return fetch(url, params) | |
.then(res => { | |
const verb = RESOLVE_STATUS_CODES.indexOf(res.status) === -1 ? 'reject' : 'resolve'; | |
return res.json() | |
.then(payload => Promise[verb](payload)); | |
}); | |
}; | |
export default request; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
Edit: handling responses status' code and reject promise accordingly.