@daiso-tech/core
Version:
The library offers flexible, framework-agnostic solutions for modern web applications, built on adaptable components that integrate seamlessly with popular frameworks like Next Js.
91 lines • 3.12 kB
JavaScript
/**
* @module Async
*/
import { resolveAsyncLazyable, callInvokable, resultSuccess, callErrorPolicyOnValue, isResultFailure, } from "../../../utilities/_module-exports.js";
import { callErrorPolicyOnThrow } from "../../../utilities/_module-exports.js";
/**
* The `fallback` middleware adds fallback value when an error occurs.
*
* IMPORT_PATH: `"@daiso-tech/core/async"`
* @group Middlewares
*
* @example
* ```ts
* import { fallback } from "@daiso-tech/core/async";
* import { AsyncHooks } from "@daiso-tech/core/utilities";
*
* const fetchData = new AsyncHooks(async (url: string): Promise<unknown> => {
* const response = await fetch(url);
* const json = await response.json();
* if (!response.ok) {
* throw json
* }
* return json;
* }, [
* fallback({ fallbackValue: null })
* ]);
*
* // Will return null when the fetch method throws an error.
* console.log(await fetchData.invoke("URL_ENDPOINT"));
* ```
*
* The middleware works also when the function returns a {@link Result | `Result`} type.
* @example
* ```ts
* import { fallback } from "@daiso-tech/core/async";
* import { AsyncHooks, Result, resultFailure, resultSuccess } from "@daiso-tech/core/utilities";
*
* const fetchData = new AsyncHooks(async (url: string): Promise<Result> => {
* const response = await fetch(url);
* const json = await response.json();
* if (!response.ok) {
* return resultFailure(json);
* }
* return resultSuccess(json);
* }, [
* fallback({ fallbackValue: null })
* ]);
*
* // Will return null when the fetch method throws an error.
* console.log(await fetchData.invoke("URL_ENDPOINT"));
* ```
*/
export function fallback(settings) {
const { fallbackValue, errorPolicy, onFallback = () => { } } = settings;
return async (args, next, { context }) => {
try {
const value = await next(...args);
// Handle fallback value if an Result type is returned
if (!(await callErrorPolicyOnValue(errorPolicy, value))) {
return value;
}
// This is only needed for type inference
if (!isResultFailure(value)) {
return value;
}
const resolvedFallbackValue = await resolveAsyncLazyable(fallbackValue);
callInvokable(onFallback, {
error: value.error,
fallbackValue: resolvedFallbackValue,
args,
context,
});
return resultSuccess(resolvedFallbackValue);
// Handle fallback value if an error is thrown
}
catch (error) {
if (!(await callErrorPolicyOnThrow(errorPolicy, error))) {
throw error;
}
const resolvedFallbackValue = await resolveAsyncLazyable(fallbackValue);
callInvokable(onFallback, {
error,
fallbackValue: resolvedFallbackValue,
args,
context,
});
return resolvedFallbackValue;
}
};
}
//# sourceMappingURL=fallback.middleware.js.map