index.ts
This file
Path
src/middleware/timeout/index.ts
58 lines · 1.6 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–58why, one step back1/**2 * @module3 * Timeout Middleware for Hono.4 */56import type { Context } from '../../context'7import { HTTPException } from '../../http-exception'8import type { MiddlewareHandler } from '../../types'910export type HTTPExceptionFunction = (context: Context) => HTTPException1112const defaultTimeoutException = new HTTPException(504, {13 message: 'Gateway Timeout',14})1516/**17 * Timeout Middleware for Hono.18 *19 * @param {number} duration - The timeout duration in milliseconds.20 * @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.21 * @returns {MiddlewareHandler} The middleware handler function.22 *23 * @example24 * ```ts25 * const app = new Hono()26 *27 * app.use(28 * '/long-request',29 * timeout(5000) // Set timeout to 5 seconds30 * )31 *32 * app.get('/long-request', async (c) => {33 * await someLongRunningFunction()34 * return c.text('Completed within time limit')35 * })36 * ```37 */38export const timeout = (39 duration: number,40 exception: HTTPExceptionFunction | HTTPException = defaultTimeoutException41): MiddlewareHandler => {42 return async function timeout(context, next) {43 let timer: number | undefined44 const timeoutPromise = new Promise<void>((_, reject) => {45 timer = setTimeout(() => {46 reject(typeof exception === 'function' ? exception(context) : exception)47 }, duration) as unknown as number48 })4950 try {51 await Promise.race([next(), timeoutPromise])52 } finally {53 if (timer !== undefined) {54 clearTimeout(timer)55 }56 }57 }58}