Skip to content

Instantly share code, notes, and snippets.

@nickav
Created February 17, 2023 23:11
Show Gist options
  • Save nickav/1830064f0ae05fbd5583d85c2e43eb81 to your computer and use it in GitHub Desktop.
Save nickav/1830064f0ae05fbd5583d85c2e43eb81 to your computer and use it in GitHub Desktop.
A nice wrapper around the browser's kind of broken fetch API
const handleFetchResponse = (resp) => {
return resp.text().then((text) => {
let data = text;
const contentType = resp.headers.get("content-type");
const isJSON = contentType && contentType.indexOf("application/json") >= 0;
if (isJSON)
{
try {
data = JSON.parse(text);
} catch (err) {
console.error('Failed to parse JSON!', err);
}
}
if (!resp.ok)
{
const error = (data && data.message) || resp.statusText;
return Promise.reject(error);
}
return data;
});
};
const fetch = {
fetch: window.fetch,
get: (url, config = null) => {
const options = {
...config,
method: 'GET',
};
return window.fetch(url, options).then(handleFetchResponse);
},
post: (url, body, config = null) => {
const options = {
...config,
method: 'POST',
headers: { 'Content-Type': 'application/json', ...config?.headers },
body: JSON.stringify(body),
};
return window.fetch(url, options).then(handleFetchResponse);
},
put: (url, body, config = null) => {
const options = {
...config,
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...config?.headers },
body: JSON.stringify(body),
};
return window.fetch(url, options).then(handleFetchResponse);
},
delete: (url, config = null) => {
const options = {
...config,
method: 'DELETE',
};
return window.fetch(url, options).then(handleFetchResponse);
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment