Skip to content

Instantly share code, notes, and snippets.

@ishan1608
Created April 14, 2020 01:37
Show Gist options
  • Save ishan1608/81d35a36cb9faf4e1a4e3b2b395f47c4 to your computer and use it in GitHub Desktop.
Save ishan1608/81d35a36cb9faf4e1a4e3b2b395f47c4 to your computer and use it in GitHub Desktop.
A simple module to abstract the details of fetch API for simple calls.
export class ApiError extends Error {
constructor(message) {
super(message);
this.name = 'ApiError';
}
}
export default {
fetch: (url, fetchOptions) => {
return fetch(url, fetchOptions)
.then((response) => {
let bodyPromise;
// Processing JSON especially
if ((response.headers.get('content-type') || []).indexOf('application/json') !== -1) {
bodyPromise = response.json();
} else {
// Falling back to "text"
bodyPromise = response.text();
}
if (!response.ok || Math.floor(response.status / 100) !== 2) {
return new Promise((resolve, reject) => {
bodyPromise.then((body) => {
const error = new ApiError(`${url}: ${response.statusText}`);
error.response = response;
error.body = body;
reject(error);
});
});
}
return bodyPromise;
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment