@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 • 2.04 kB
JavaScript
/**
* @module Resilience
*/
import {} from "../../../execution-context/contracts/_module.js";
import {} from "../../../middleware/contracts/_module.js";
import { TimeoutResilienceError } from "../../../resilience/implementations/resilience.errors.js";
import { TO_MILLISECONDS, } from "../../../time-span/contracts/_module.js";
import { TimeSpan } from "../../../time-span/implementations/_module.js";
import { callInvokable } from "../../../utilities/_module.js";
/**
* The `timeout` middleware automatically cancels functions after a specified time period, throwing an error when aborted.
*
* IMPORT_PATH: `"@daiso-tech/core/resilience"`
* @group Middlewares
* @throws {TimeoutResilienceError}
*/
export function timeout(settings = {}) {
const { waitTime = TimeSpan.fromSeconds(2), onTimeout = () => { } } = settings;
return async ({ args, next, context }) => {
const timeoutError = TimeoutResilienceError.create(TimeSpan.fromTimeSpan(waitTime));
try {
let timeoutId = null;
try {
const promise = new Promise((_resolve, reject) => {
timeoutId = setTimeout(() => {
reject(timeoutError);
}, waitTime[TO_MILLISECONDS]());
});
return await Promise.race([next(), promise]);
}
finally {
if (timeoutId !== null) {
clearTimeout(timeoutId);
}
}
}
catch (error) {
if (error instanceof TimeoutResilienceError &&
error === timeoutError) {
try {
await callInvokable(onTimeout, {
args,
context,
waitTime: TimeSpan.fromTimeSpan(waitTime),
});
}
catch {
/* EMPTY */
}
}
throw error;
}
};
}
//# sourceMappingURL=timeout.js.map