Created
April 14, 2020 01:37
-
-
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.
This file contains hidden or 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
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