@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.
55 lines (54 loc) • 1.91 kB
TypeScript
/**
* @module Async
*/
import { type HookContext } from "../../../utilities/_module-exports.js";
import type { AsyncMiddlewareFn } from "../../../utilities/_module-exports.js";
import type { FallbackSettings } from "../../../async/middlewares/fallback/fallback.types.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 declare function fallback<TParameters extends unknown[], TReturn, TContext extends HookContext>(settings: NoInfer<FallbackSettings<TParameters, TReturn, TContext, TReturn>>): AsyncMiddlewareFn<TParameters, TReturn, TContext>;