Middleware Combine
Le middleware Combine associe plusieurs fonctions middleware dans un seul middleware. Il fournit trois fonctions :
some- Exécute un seul des middlewares fournis.every- Exécute tous les middlewares fournis.except- Exécute tous les middlewares fournis uniquement si une condition n’est pas remplie.
Importation
import { Hono } from 'hono'
import { some, every, except } from 'hono/combine'Utilisation
Voici un exemple de règles de contrôle d’accès complexes utilisant le middleware Combine.
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
Exécute le premier middleware qui renvoie true. Les middlewares sont appliqués dans l’ordre ; dès qu’un middleware se termine avec succès, les suivants ne sont pas exécutés.
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
Exécute tous les middlewares et s’arrête si l’un d’eux échoue. Les middlewares sont appliqués dans l’ordre ; si l’un d’eux lève une erreur, les suivants ne sont pas exécutés.
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
Exécute tous les middlewares sauf lorsque la condition est remplie. Vous pouvez passer une chaîne ou une fonction comme condition. Pour faire correspondre plusieurs cibles, passez-les dans un tableau.
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 })))