Skip to content

Instantly share code, notes, and snippets.

@sidevesh
Last active April 30, 2020 11:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidevesh/adaf910bc384574b776c370f77b9bedf to your computer and use it in GitHub Desktop.
Save sidevesh/adaf910bc384574b776c370f77b9bedf to your computer and use it in GitHub Desktop.
fetchHandler - handle api calls to your Backend with fetch api in a simple and unified way
const responseParserTypes = {
json: (response) => response.json(),
text: (response) => response.text(),
blob: (response) => response.blob(),
formData: (response) => response.formData(),
arrayBuffer: (response) => response.arrayBuffer(),
};
const parseResponse = (response, type) => {
if (!Object.keys(responseParserTypes).includes(type)) {
return null;
}
return responseParserTypes[type](response);
};
const fetchHandler = (
fetchPromise,
{
handledStatusCodes = [200],
parseHandledResponseAs = 'json',
parseUnhandledResponseAs = 'text',
getUnhandledResponseMessage = () => 'Error occured',
getFailureMessage = () => 'Error occured',
},
) => {
if (!Object.keys(responseParserTypes).includes(parseHandledResponseAs)) {
throw new Error(`parseHandledResponseAs shouwld be one of [${Object.keys(responseParserTypes).join(', ')}]`);
}
if (!Object.keys(responseParserTypes).includes(parseUnhandledResponseAs)) {
throw new Error(`parseUnhandledResponseAs shouwld be one of [${Object.keys(responseParserTypes).join(', ')}]`);
}
return new Promise((resolve, reject) => {
fetchPromise
.then((response) => {
if (handledStatusCodes.includes(response.status)) {
const parseResponsePromise = parseResponse(response, parseHandledResponseAs);
parseResponsePromise
.then((parsedResponse) => resolve(parsedResponse))
.catch((e) => reject(getFailureMessage(e)));
} else {
const parseResponsePromise = parseResponse(response, parseUnhandledResponseAs);
parseResponsePromise
.then((parsedResponse) => reject(getUnhandledResponseMessage(
response.status,
parsedResponse,
)))
.catch((e) => reject(getFailureMessage(e)));
}
})
.catch((e) => reject(getFailureMessage(e)));
});
};
export default fetchHandler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment