App - Hono
Hono
は主要なオブジェクトです。最初にインポートされ、最後まで使用されます。
import { Hono } from 'hono'
const app = new Hono()
//...
export default app // for Cloudflare Workers or Bun
メソッド
Hono
のインスタンスには、次のメソッドがあります。
- app.HTTP_METHOD([path,]handler|middleware...)
- app.all([path,]handler|middleware...)
- app.on(method|method[], path|path[], handler|middleware...)
- app.use([path,]middleware)
- app.route(path, [app])
- app.basePath(path)
- app.notFound(handler)
- app.onError(err, handler)
- app.mount(path, anotherApp)
- app.fire()
- app.fetch(request, env, event)
- app.request(path, options)
これらの最初の部分はルーティングに使用されます。 ルーティングセクションを参照してください。
Not Found
app.notFound
を使用すると、Not Foundレスポンスをカスタマイズできます。
app.notFound((c) => {
return c.text('Custom 404 Message', 404)
})
エラー処理
app.onError
はエラーを処理し、カスタマイズされたResponseを返します。
app.onError((err, c) => {
console.error(`${err}`)
return c.text('Custom Error Message', 500)
})
fire()
app.fire()
は、グローバルなfetch
イベントリスナーを自動的に追加します。
これは、Service Worker APIに準拠した環境、たとえば非ESモジュールCloudflare Workersなどで役立ちます。
app.fire()
は次の処理を実行します。
addEventListener('fetch', (event: FetchEventLike): void => {
event.respondWith(this.dispatch(...))
})
fetch()
app.fetch
は、アプリケーションのエントリーポイントになります。
Cloudflare Workersの場合、次のように使用できます。
export default {
fetch(request: Request, env: Env, ctx: ExecutionContext) {
return app.fetch(request, env, ctx)
},
}
または、次のようにすることもできます。
export default app
Bun
export default app
export default {
port: 3000,
fetch: app.fetch,
}
request()
request
はテストに役立つメソッドです。
URLまたはパス名を渡して、GETリクエストを送信できます。app
はResponse
オブジェクトを返します。
test('GET /hello is ok', async () => {
const res = await app.request('/hello')
expect(res.status).toBe(200)
})
Request
オブジェクトを渡すこともできます。
test('POST /message is ok', async () => {
const req = new Request('Hello!', {
method: 'POST',
})
const res = await app.request(req)
expect(res.status).toBe(201)
})
mount()
mount()
を使用すると、他のフレームワークで構築されたアプリケーションをHonoアプリケーションにマウントできます。
import { Router as IttyRouter } from 'itty-router'
import { Hono } from 'hono'
// Create itty-router application
const ittyRouter = IttyRouter()
// Handle `GET /itty-router/hello`
ittyRouter.get('/hello', () => new Response('Hello from itty-router'))
// Hono application
const app = new Hono()
// Mount!
app.mount('/itty-router', ittyRouter.handle)
strictモード
strictモードはデフォルトでtrue
に設定されており、次のルートを区別します。
/hello
/hello/
app.get('/hello')
はGET /hello/
に一致しません。
strictモードをfalse
に設定すると、両方のパスが同じように扱われます。
const app = new Hono({ strict: false })
routerオプション
router
オプションは、使用するルーターを指定します。デフォルトのルーターはSmartRouter
です。RegExpRouter
を使用する場合は、新しいHono
インスタンスに渡します。
import { RegExpRouter } from 'hono/router/reg-exp-router'
const app = new Hono({ router: new RegExpRouter() })
ジェネリクス
ジェネリクスを渡して、c.set
/c.get
で使用されるCloudflare Workers Bindingsと変数の型を指定できます。
type Bindings = {
TOKEN: string
}
type Variables = {
user: User
}
const app = new Hono<{
Bindings: Bindings
Variables: Variables
}>()
app.use('/auth/*', async (c, next) => {
const token = c.env.TOKEN // token is `string`
// ...
c.set('user', user) // user should be `User`
await next()
})