Files
SnowLuma/.pnpm-store/v11/files/57/87d3e04b4d9329dd6eb61dd91d81f8f8e5a77720016ad4fbb960b69ab3d6bab866a9640db25af5e8418ddb648da5004f00aa888f938221eb5535d3c9202099
TanTan 2a69b23b47
Dev Build / cleanup (push) Canceled after 0s
Dev Build / typecheck (push) Canceled after 0s
Dev Build / build (linux-arm64, ubuntu-24.04-arm, linux-arm64) (push) Canceled after 0s
Dev Build / build (linux-x64, ubuntu-latest, linux-x64) (push) Canceled after 0s
Dev Build / build (win-x64, windows-latest, win32-x64) (push) Canceled after 0s
Dev Build / dispatch-dev-docker (push) Skipped
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

43 lines
1.3 KiB
Plaintext

Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
//#region src/middleware/timeout/index.ts
const defaultTimeoutException = new (require("../../http-exception.js")).HTTPException(504, { message: "Gateway Timeout" });
/**
* Timeout Middleware for Hono.
*
* @param {number} duration - The timeout duration in milliseconds.
* @param {HTTPExceptionFunction | HTTPException} [exception=defaultTimeoutException] - The exception to throw when the timeout occurs. Can be a function that returns an HTTPException or an HTTPException object.
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use(
* '/long-request',
* timeout(5000) // Set timeout to 5 seconds
* )
*
* app.get('/long-request', async (c) => {
* await someLongRunningFunction()
* return c.text('Completed within time limit')
* })
* ```
*/
const timeout = (duration, exception = defaultTimeoutException) => {
return async function timeout(context, next) {
let timer;
const timeoutPromise = new Promise((_, reject) => {
timer = setTimeout(() => {
reject(typeof exception === "function" ? exception(context) : exception);
}, duration);
});
try {
await Promise.race([next(), timeoutPromise]);
} finally {
if (timer !== void 0) clearTimeout(timer);
}
};
};
//#endregion
exports.timeout = timeout;