Skip to content

Instantly share code, notes, and snippets.

@grabcode
Last active July 5, 2017 03:44
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 grabcode/f18c427bfb89a5c392a2ca6ed4b8a0ac to your computer and use it in GitHub Desktop.
Save grabcode/f18c427bfb89a5c392a2ca6ed4b8a0ac to your computer and use it in GitHub Desktop.
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;
@grabcode
Copy link
Author

grabcode commented Jul 3, 2017

Edit: handling responses status' code and reject promise accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment