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.

60 lines 2.05 kB
/** * @module Async */ import { TimeSpan } from "../../../utilities/_module-exports.js"; import {} from "../../../utilities/_module-exports.js"; import { callInvokable } from "../../../utilities/_module-exports.js"; import { TimeoutAsyncError } from "../../../async/async.errors.js"; import { timeoutAndFail } from "../../../async/utilities/_module.js"; /** * The `timeout` middleware automatically cancels functions after a specified time period, throwing an error when aborted. * Note the original function continues executing (even if the promise fails), you'll need to provide a settings.signalBinder to forward the `AbortSignal`. * * IMPORT_PATH: `"@daiso-tech/core/async"` * @group Middlewares * @throws {TimeoutAsyncError} {@link TimeoutAsyncError} * * @example * ```ts * import { timeout } from "@daiso-tech/core/async"; * import { AsyncHooks, TimeSpan } from "@daiso-tech/core/utilities"; * * const data = await new AsyncHooks( * async (url: string, signal?: AbortSignal): Promise<unknown> => { * const response = await fetch(url, { signal }); * return await response.json(); * }, * [timeout({ waitTime: TimeSpan.fromSeconds(2) })], * { * signalBinder: { * getSignal: (args) => args[1], * forwardSignal: (args, signal) => { * args[1] = signal; * } * } * } * ) * .invoke("URL"); * ``` */ export function timeout(settings = {}) { const { waitTime = TimeSpan.fromSeconds(2), onTimeout = () => { } } = settings; return async (args, next, { context, abort, signal }) => { try { return await timeoutAndFail(next(...args), waitTime, (error) => { abort(error); }, signal); } catch (error) { if (error instanceof TimeoutAsyncError) { callInvokable(onTimeout, { args, context, waitTime, }); } throw error; } }; } //# sourceMappingURL=timeout.middleware.js.map