Skip to content

Instantly share code, notes, and snippets.

@cisoun
Created January 29, 2020 12:20
Show Gist options
  • Save cisoun/e872ba5f679452b70b672656b873a574 to your computer and use it in GitHub Desktop.
Save cisoun/e872ba5f679452b70b672656b873a574 to your computer and use it in GitHub Desktop.
Wrapper for window.fetch that handles JSON responses
/**
* 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