Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fetch api client
class APIError extends Error {
constructor(response) {
super(response.message);
this.name = 'APIError';
this.code = `errors.${response.code}`;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
this.stack = new Error().stack;
}
}
}
// request is a wrapper around fetch to throw errors on HTTP error codes and parse json
const request = (url, options) =>
fetch(url, options).then(response => {
if (response.status >= 200 && response.status < 300) {
return response.status === 204 || response.status === 205 ? null : response.json();
}
return response.json().then(res => {
throw new APIError(res);
});
});
export default request;
export const makeRequest = (method, url, body, options) => {
return request(url, {
credentials: 'include',
method,
mode: 'cors',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8'
},
...options,
body: JSON.stringify(body)
});
};
export const get = (url, body, options) => makeRequest('GET', url, body, options);
export const post = (url, body, options) => makeRequest('POST', url, body, options);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment