Last active
July 5, 2017 03:44
-
-
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
This file contains 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
/* | |
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
Edit: handling responses status' code and reject promise accordingly.