Files
SnowLuma/.pnpm-store/v11/files/56/efb801aae9c58a188794171f9332dd4d23bb7c6cadb79644720ec93b61135112b18a7128f4249eed505e4c9bac536db2d2de7b0acb17b4093a6fe533edfab1
T
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) Canceled after 0s
docs: 仓库链接指向本镜像仓库
2026-11-13 09:27:07 +08:00

43 lines
1.3 KiB
Plaintext

import { HTTPException } from "../../http-exception.js";
//#region src/middleware/timeout/index.ts
const defaultTimeoutException = new 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
export { timeout };