Created
January 29, 2020 12:20
-
-
Save cisoun/e872ba5f679452b70b672656b873a574 to your computer and use it in GitHub Desktop.
Wrapper for window.fetch that handles JSON responses
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
/** | |
* Custom wrapper using the Fetch API. | |
*/ | |
const Fetch = { | |
async get (url) { return this.request(url, 'GET'); }, | |
async post (url, data={}) { return this.request(url, 'POST', data); }, | |
/** | |
* Do a request. | |
* | |
* @param {string} url URL to fetch. | |
* @param {string} method Fetch method (GET/POST/...). | |
* @param {object} data (Optional) JSON data to send (POST/UPDATE only). | |
* @return {object} Dictionary containing status, success and data. | |
*/ | |
async request(url, method, data={}) { | |
let params = { method: method }; | |
// Add JSON data if necessary. | |
if (['PATCH', 'POST', 'PUT'].includes(method)) { | |
params = Object.assign(params, { | |
body: JSON.stringify(data), | |
headers: { 'Content-Type': 'application/json' }, | |
}); | |
} | |
const response = await fetch(url, params); | |
return { | |
'status': response.status, | |
'ok': response.ok, | |
'data': await response.json() | |
}; | |
}, | |
}; | |
export default Fetch; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment