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.

46 lines 1.65 kB
/** * @module Async */ import { callInvokable, TimeSpan, } from "../../../utilities/_module-exports.js"; import { PromiseQueue } from "../../../async/utilities/_module.js"; /** * The `bulkhead` middlewares ensures that a given amount of {@link Promiselike | `PromiseLike`} objects run at the same time concurrently and the rest will be queued up. * You can provide {@link BulkheadSettings | `settings.maxCapacity`} * * IMPORT_PATH: `"@daiso-tech/core/async"` * @group Middlewares * @throws {CapacityFullAsyncError} {@link CapacityFullAsyncError} * ```ts * import { bulkhead } 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(); * return json; * }, [ * bulkhead() * ]); * * // Will run only 25 promises concurrently by default. * await Promise.all(Array(50).fill("").map(() => fetchData.invoke("URL"))); * ``` */ export function bulkhead(settings = {}) { const { maxConcurrency = 25, maxCapacity = null, interval = TimeSpan.fromMilliseconds(0), onProcessing = () => { }, } = settings; const promiseQueue = new PromiseQueue({ maxCapacity, maxConcurrency, interval, }); return async (args, next, { context, signal }) => { return await promiseQueue.add(() => { callInvokable(onProcessing, { args, context, }); return next(...args); }, signal); }; } //# sourceMappingURL=bulkhead.middleware.js.map