Skip to content

Instantly share code, notes, and snippets.

@caub
Last active October 28, 2021 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caub/7494b4391c2d62c49b565d2cfc2c0c1f to your computer and use it in GitHub Desktop.
Save caub/7494b4391c2d62c49b565d2cfc2c0c1f to your computer and use it in GitHub Desktop.
Simple fetch wrapper
const API_URL = 'https://..'; // Your API base url
// returns true for plain object literals, like {foo: 'bar'}, false for other cases, like instances of classes, like lodash.isPlainObject
const isPlainObject = obj => obj && Object.getPrototypeOf(obj) === Object.prototype || Object.getPrototypeOf(obj) === null;
export function fetchJson(url, { body, headers, ...o } = {}) {
const isJson = isPlainObject(body); // most of the time we send plain 'json' objects
return fetch(url[0] === '/' ? API_URL + url : url, {
headers: {
...isJson && {'Content-Type': 'application/json'},
...headers
},
body: isJson ? JSON.stringify(body) : body,
...o
}).then(async r => {
const data = await r.json().catch(() => ({}));
if (r.ok) return data;
// your logic to extract error message:
const err = new Error(data && data.message || data);
err.status = r.status;
throw err;
});
}
export default {
get: (url, opts) => fetchJson(url, {method: 'GET', ...opts}),
post: (url, body, opts) => fetchJson(url, {method: 'POST', body, ...opts}),
put: (url, body, opts) => fetchJson(url, {method: 'PUT', body, ...opts}),
delete: (url, opts) => fetchJson(url, {method: 'DELETE', ...opts}),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment