コンテンツへスキップ

App - Hono

Honoは主要なオブジェクトです。最初にインポートされ、最後まで使用されます。

ts
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レスポンスをカスタマイズできます。

ts
app
.
notFound
((
c
) => {
return
c
.
text
('Custom 404 Message', 404)
})

エラー処理

app.onErrorはエラーを処理し、カスタマイズされたResponseを返します。

ts
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()は次の処理を実行します。

ts
addEventListener('fetch', (event: FetchEventLike): void => {
  event.respondWith(this.dispatch(...))
})

fetch()

app.fetchは、アプリケーションのエントリーポイントになります。

Cloudflare Workersの場合、次のように使用できます。

ts
export default {
  
fetch
(
request
: Request,
env
:
Env
,
ctx
:
ExecutionContext
) {
return
app
.
fetch
(
request
,
env
,
ctx
)
}, }

または、次のようにすることもできます。

ts
export default 
app

Bun

ts
export default app 
export default {  
  port: 3000, 
  fetch: app.fetch, 
} 

request()

requestはテストに役立つメソッドです。

URLまたはパス名を渡して、GETリクエストを送信できます。appResponseオブジェクトを返します。

ts
test
('GET /hello is ok', async () => {
const
res
= await
app
.
request
('/hello')
expect
(
res
.
status
).toBe(200)
})

Requestオブジェクトを渡すこともできます。

ts
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アプリケーションにマウントできます。

ts
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に設定すると、両方のパスが同じように扱われます。

ts
const 
app
= new
Hono
({
strict
: false })

routerオプション

routerオプションは、使用するルーターを指定します。デフォルトのルーターはSmartRouterです。RegExpRouterを使用する場合は、新しいHonoインスタンスに渡します。

ts
import { 
RegExpRouter
} from 'hono/router/reg-exp-router'
const
app
= new
Hono
({
router
: new
RegExpRouter
() })

ジェネリクス

ジェネリクスを渡して、c.set/c.getで使用されるCloudflare Workers Bindingsと変数の型を指定できます。

ts
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
()
})

MITライセンスの下でリリースされています。