跳至內容

逾時中間件

逾時中間件讓您能夠輕鬆管理應用程式中的請求逾時。它允許您為請求設定最大持續時間,並可選擇在超過指定的逾時時間時定義自訂錯誤回應。

匯入

ts
import { Hono } from 'hono'
import { timeout } from 'hono/timeout'

用法

以下說明如何使用預設和自訂設定的逾時中間件

預設設定

ts
const app = new Hono()

// Applying a 5-second timeout
app.use('/api', timeout(5000))

// Handling a route
app.get('/api/data', async (c) => {
  // Your route handler logic
  return c.json({ data: 'Your data here' })
})

自訂設定

ts
import { HTTPException } from 'hono/http-exception'

// Custom exception factory function
const customTimeoutException = (context) =>
  new HTTPException(408, {
    message: `Request timeout after waiting ${context.req.headers.get(
      'Duration'
    )} seconds. Please try again later.`,
  })

// for Static Exception Message
// const customTimeoutException = new HTTPException(408, {
//   message: 'Operation timed out. Please try again later.'
// });

// Applying a 1-minute timeout with a custom exception
app.use('/api/long-process', timeout(60000, customTimeoutException))

app.get('/api/long-process', async (c) => {
  // Simulate a long process
  await new Promise((resolve) => setTimeout(resolve, 61000))
  return c.json({ data: 'This usually takes longer' })
})

注意事項

  • 逾時時間的持續時間可以毫秒為單位指定。如果超過指定的持續時間,中間件會自動拒絕 promise,並可能拋出錯誤。

  • 逾時中間件不能與串流一起使用。因此,請將 stream.closesetTimeout 一起使用。

ts
app.get('/sse', async (c) => {
  let id = 0
  let running = true
  let timer: number | undefined

  return streamSSE(c, async (stream) => {
    timer = setTimeout(() => {
      console.log('Stream timeout reached, closing stream')
      stream.close()
    }, 3000) as unknown as number

    stream.onAbort(async () => {
      console.log('Client closed connection')
      running = false
      clearTimeout(timer)
    })

    while (running) {
      const message = `It is ${new Date().toISOString()}`
      await stream.writeSSE({
        data: message,
        event: 'time-update',
        id: String(id++),
      })
      await stream.sleep(1000)
    }
  })
})

中間件衝突

請注意中間件的順序,尤其是在使用錯誤處理或其他與時間相關的中間件時,因為它可能會影響此逾時中間件的行為。

根據 MIT 許可發布。