Combine 中间件
Combine 中间件将多个中间件函数组合为一个中间件,提供三个函数:
some- 仅运行给定中间件中的一个。every- 运行所有给定中间件。except- 仅在条件不满足时运行所有给定中间件。
导入
ts
import { Hono } from 'hono'
import { some, every, except } from 'hono/combine'用法
以下是使用 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 '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
运行所有中间件,任何一个失败时就停止。中间件按顺序应用;如果某个中间件抛出错误,后续中间件就不会运行。
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 })))