Skip to content

Instantly share code, notes, and snippets.

@abemedia
Created April 19, 2020 00:26
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 abemedia/6941e129f4ce4477f76f84a085cc8946 to your computer and use it in GitHub Desktop.
Save abemedia/6941e129f4ce4477f76f84a085cc8946 to your computer and use it in GitHub Desktop.
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