Last active
October 28, 2021 18:18
-
-
Save caub/7494b4391c2d62c49b565d2cfc2c0c1f to your computer and use it in GitHub Desktop.
Simple fetch wrapper
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
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