跳至內容

組合中間件

組合中間件將多個中間件函數合併為一個單一的中間件。它提供三個函數

  • some - 只執行給定的中間件中的一個。
  • every - 執行所有給定的中間件。
  • except - 只有在不符合條件時才執行所有給定的中間件。

匯入

ts
import { Hono } from 'hono'
import { some, every, except } from 'hono/combine'

用法

以下是使用組合中間件進行複雜存取控制規則的範例。

ts
import { Hono } from 'hono'
import { bearerAuth } from 'hono/bearer-auth'
import { getConnInfo } from 'hono/cloudflare-workers'
import { every, some } from 'hono/combine'
import { ipRestriction } from 'hono/ip-restriction'
import { rateLimit } from '@/my-rate-limit'

const app = new Hono()

app.use(
  '*',
  some(
    every(
      ipRestriction(getConnInfo, { allowList: ['192.168.0.2'] }),
      bearerAuth({ token })
    ),
    // If both conditions are met, rateLimit will not execute.
    rateLimit()
  )
)

app.get('/', (c) => c.text('Hello Hono!'))

some

執行第一個傳回 true 的中間件。中間件依序應用,如果任何中間件成功退出,則後續中間件將不會執行。

ts
import { some } from 'combine'
import { bearerAuth } from 'bearer-auth'
import { myRateLimit } from '@/rate-limit'

// If client has a valid token, skip rate limiting.
// Otherwise, apply rate limiting.
app.use(
  '/api/*',
  some(bearerAuth({ token }), myRateLimit({ limit: 100 }))
)

every

執行所有中間件,如果其中任何一個失敗則停止。中間件依序應用,如果任何中間件拋出錯誤,則後續中間件將不會執行。

ts
import { some, every } from 'hono/combine'
import { bearerAuth } from 'hono/bearer-auth'
import { myCheckLocalNetwork } from '@/check-local-network'
import { myRateLimit } from '@/rate-limit'

// If client is in local network, skip authentication and rate limiting.
// Otherwise, apply authentication and rate limiting.
app.use(
  '/api/*',
  some(
    myCheckLocalNetwork(),
    every(bearerAuth({ token }), myRateLimit({ limit: 100 }))
  )
)

except

除非滿足條件,否則執行所有中間件。您可以將字串或函數作為條件傳遞。如果需要比對多個目標,請將它們作為陣列傳遞。

ts
import { except } from 'hono/combine'
import { bearerAuth } from 'hono/bearer-auth'

// If client is accessing public API, skip authentication.
// Otherwise, require a valid token.
app.use('/api/*', except('/api/public/*', bearerAuth({ token })))

在 MIT 授權下發布。