Skip to content

Instantly share code, notes, and snippets.

@SiDevesh SiDevesh/fetchHandler.js
Last active Apr 30, 2020

Embed
What would you like to do?
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
You can’t perform that action at this time.