Skip to content

合并中间件

¥Combine Middleware

Combine Middleware 将多个中间件函数组合成一个中间件。它提供了三个功能:

¥Combine Middleware combines multiple middleware functions into a single middleware. It provides three functions:

  • some - 仅运行给定的中间件之一。

    ¥some - Runs only one of the given middleware.

  • every - 运行所有给定的中间件。

    ¥every - Runs all given middleware.

  • except - 仅在条件不满足时运行所有给定的中间件。

    ¥except - Runs all given middleware only if a condition is not met.

导入

¥Import

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

用法

¥Usage

以下是使用 Combine Middleware 的复杂访问控制规则的示例。

¥Here's an example of complex access control rules using Combine Middleware.

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 的中间件。中间件按顺序应用,如果任何一个中间件成功退出,后续的中间件将不会运行。

¥Runs the first middleware that returns true. Middleware is applied in order, and if any middleware exits successfully, subsequent middleware will not run.

ts
import { some } from 'hono/combine'
import { bearerAuth } from 'hono/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

运行所有中间件,如果任何一个失败则停止。中间件按顺序应用,如果任何一个中间件抛出错误,后续的中间件将不会运行。

¥Runs all middleware and stops if any of them fail. Middleware is applied in order, and if any middleware throws an error, subsequent middleware will not run.

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

运行所有中间件,除非满足条件。你可以传递字符串或函数作为条件。如果需要匹配多个目标,请将它们作为数组传递。

¥Runs all middleware except when the condition is met. You can pass a string or function as the condition. If multiple targets need to be matched, pass them as an array.

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 })))

Hono v4.7 中文网 - 粤ICP备13048890号