Skip to content

미들웨어 결합

미들웨어 결합 기능은 여러 미들웨어 함수를 하나로 통합한다. 이 기능은 세 가지 주요 함수를 제공한다:

  • some: 주어진 미들웨어 중 하나만 실행한다.
  • every: 주어진 모든 미들웨어를 실행한다.
  • except: 특정 조건이 충족되지 않을 때만 주어진 모든 미들웨어를 실행한다.

Import

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

사용 방법

아래는 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 })
    ),
    // 두 조건이 모두 충족되면 rateLimit는 실행되지 않는다.
    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'

// 클라이언트가 유효한 토큰을 가지고 있다면, rate limiting을 건너뛴다.
// 그렇지 않으면 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'

// 클라이언트가 로컬 네트워크에 있으면 인증과 속도 제한을 건너뛴다.
// 그렇지 않으면 인증과 속도 제한을 적용한다.
app.use(
  '/api/*',
  some(
    myCheckLocalNetwork(),
    every(bearerAuth({ token }), myRateLimit({ limit: 100 }))
  )
)

except

조건이 충족될 때만 미들웨어를 실행하지 않는다. 조건으로 문자열이나 함수를 전달할 수 있다. 여러 대상을 매칭해야 한다면 배열로 전달한다.

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

// 클라이언트가 공개 API에 접근할 때는 인증을 건너뛴다.
// 그 외의 경우에는 유효한 토큰을 요구한다.
app.use('/api/*', except('/api/public/*', bearerAuth({ token })))

Released under the MIT License.