fetchHandler - handle api calls to your Backend with fetch api in a simple and unified way
This file contains 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
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