Skip to content

Instantly share code, notes, and snippets.

@caub caub/fetchJson.js
Last active Aug 23, 2019

Embed
What would you like to do?
const API_URL = 'https://..';
// returns true for plain object literals, like {foo: 'bar'}, false for other cases, like instances of classes
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: {
...localStorage.getItem('accessToken') && {'Authorization': 'Bearer ' + localStorage.getItem('accessToken')},
...isJson && {'Content-Type': 'application/json'},
...headers
},
body: isJson ? JSON.stringify(body) : body,
...o
}).then(async r => {
if (r.ok) return r.json().catch(() => ({}));
let data = await r.text(); // error responses can be text
try {
data = JSON.parse(message);
} catch { }
if (r.status === 401) {
localStorage.removeItem('accessToken');
}
// your logic to extract error message:
const err = new Error(data && data.message || data);
err.status = r.status;
throw err;
});
}
// for axios fans
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
You can’t perform that action at this time.