本文へ移動

Combine ミドルウェア ​

Combine ミドルウェアは、複数のミドルウェア関数を 1 つのミドルウェアにまとめます。次の 3 つの関数を提供します。

  • some - 指定したミドルウェアのうち 1 つだけを実行します。
  • 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 })))

MIT ライセンスで公開されています。