本文へ移動

Mount ミドルウェア ​

Mount ミドルウェアは、別のフレームワークで構築したアプリケーションを Hono アプリケーションにマウントできます。

インポート ​

ts
import { 
Hono
} from 'hono'
import {
mount
} from 'hono/mount'

使い方 ​

app.all() で、/* で終わるパスにミドルウェアを登録します。

ts
import { Router as IttyRouter } from 'itty-router'

// Create itty-router application
const ittyRouter = IttyRouter()

// Handle `GET /itty-router/hello`
ittyRouter.get('/hello', () => new Response('Hello from itty-router'))

const app = new Hono()

app.all('/itty-router/*', mount(ittyRouter.handle))

デフォルトでは、マウントしたアプリケーションに、URL からマッチしたパスのプレフィックスを除いた新しい Request が渡されます。/itty-router/hello へのリクエストは、itty-router に /hello として届きます。

マウントしたアプリケーションは、Cloudflare Workers の fetch ハンドラーと同じ引数で、handler(request, c.env, c.executionCtx) として呼び出されます。異なる引数を渡すには optionHandler を使用します。

オプション ​

第 2 引数には関数またはオブジェクトを渡せます。

optional optionHandler: (c: Context) => unknown ​

マウントしたアプリケーションに、Request の後で渡す引数を返します。配列は複数の引数に展開されます。この関数は第 2 引数に直接渡せます。

ts
// Call `anotherApp(request, c.env)`
app
.
all
(
'/app/*',
mount
(
anotherApp
, (
c
) =>
c
.
env
)
) // Call `anotherApp(request, c.env, c.executionCtx)`
app
.
all
(
'/app/*',
mount
(
anotherApp
, {
optionHandler
: (
c
) => [
c
.
env
,
c
.
executionCtx
],
}) )

optional replaceRequest: ((originalRequest: Request) => Request) | false ​

マウントしたアプリケーションに渡す Request を制御します。

ts
// `/legacy/users` reaches the mounted application as `/api/users`
app
.
all
(
'/legacy/*',
mount
(
anotherApp
, {
replaceRequest
: (
req
) => {
const
url
= new
URL
(
req
.
url
)
url
.
pathname
=
url
.
pathname
.
replace
(/^\/legacy/, '/api')
return new
Request
(
url
,
req
)
}, }) )

元の Request を変更せずに渡すには、(req) => req の省略形として false を設定します。

ts
app
.
all
(
'/app/*',
mount
(
anotherApp
, {
replaceRequest
: false,
}) )

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