0.0.5 • Published 5 years ago
with-fallback v0.0.5
with-fallback
Wraps a function with a fallback value which will be returned in case the function fails.
setup
npm install with-fallbackusage
import withFallback from 'with-fallback'
async function fetchUserImage(uid) {
const userResponse = await fetch(`https://my-server/api/users/${uid}`);
const userDto = await userResponse.json();
return userDto.image;
}
const defaultImage = {
url: 'default_profile.png',
width: 50,
height: 50,
};
const userImage = withFallback(() => fetchUserImage(1), defaultImage);Api
withFallback(fetcher, fallback, options):
Arguments:
- fetcher:
() => Promise<ValueType>- an async / sync function that returns a value of type \. - fallback:
ValueType- a fallback value of type \ that will be returned in casefetcherfails (throws) - options:
WithFallbackOptions:- logger:
(error: Any) => void- a logger which will be invoked when a fallback occours. (default logger isconsole.log) - retry:
RetryOptions:- amount:
number- the maximum amount of retries to perform (default amount is0) - duration:
number- waiting time between retries - in ms (default duration is1000ms)
- amount:
- verifier:
(response: ValueType) => boolean- a function that verifies the response if it didn't throw an error - backupFetcher:
() => Promise<ValueType>- a secondary fetcher that will be tried if the main fetcher fails (it will invoke alternatively when usingretryand beverifiedandlogged)
- logger:
Return Value:
Promise<ValueType>
fetchResponseVerifier:
Provide as a verifier to handle fetchApi requests
import withFallback, { fetchResponseVerifier } from 'with-fallback'
const userImage = withFallback(() => fetch(`https://my-server/api/users/${uid}`), fallback, {
verifier: fetchResponseVerfier
});This verifies that the response is "ok"
Typescript Support
withFallback is strongly typed. And it enforces the fallback value to be of the same type as the fetcher's return value.