UNPKG

@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.

52 lines 1.58 kB
/** * @module Async */ import { callInvokable, resolveAsyncLazyable, } 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")); * ``` */ export function fallback(settings) { const { fallbackValue, fallbackPolicy = () => true, onFallback = () => { }, } = settings; return async (args, next, { context }) => { try { return await next(...args); } catch (error) { if (callInvokable(fallbackPolicy, error)) { const resolvedFallbackValue = await resolveAsyncLazyable(fallbackValue); callInvokable(onFallback, { error, fallbackValue: resolvedFallbackValue, args, context, }); return resolvedFallbackValue; } throw error; } }; } //# sourceMappingURL=fallback.middleware.js.map