ファクトリヘルパー
ファクトリヘルパーは、ミドルウェアなど、Honoのコンポーネントを作成するための便利な関数を提供します。適切なTypeScript型を設定するのが難しい場合がありますが、このヘルパーはその作業を容易にします。
インポート
ts
import { Hono } from 'hono'
import { createFactory, createMiddleware } from 'hono/factory'
createFactory()
createFactory()
は、Factoryクラスのインスタンスを作成します。
ts
import { createFactory } from 'hono/factory'
const factory = createFactory()
ジェネリクスとしてEnv型を渡すことができます。
ts
type Env = {
Variables: {
foo: string
}
}
const factory = createFactory<Env>()
createMiddleware()
createMiddleware()
はfactory.createMiddleware()
のショートカットです。この関数はカスタムミドルウェアを作成します。
ts
const messageMiddleware = createMiddleware(async (c, next) => {
await next()
c.res.headers.set('X-Message', 'Good morning!')
})
ヒント: message
のような引数を取得したい場合は、次のように関数として作成できます。
ts
const messageMiddleware = (message: string) => {
return createMiddleware(async (c, next) => {
await next()
c.res.headers.set('X-Message', message)
})
}
app.use(messageMiddleware('Good evening!'))
factory.createHandlers()
createHandlers()
は、app.get('/')
とは別の場所でハンドラーを定義するのに役立ちます。
ts
import { createFactory } from 'hono/factory'
import { logger } from 'hono/logger'
// ...
const factory = createFactory()
const middleware = factory.createMiddleware(async (c, next) => {
c.set('foo', 'bar')
await next()
})
const handlers = factory.createHandlers(logger(), middleware, (c) => {
return c.json(c.var.foo)
})
app.get('/api', ...handlers)
factory.createApp()
実験的
createApp()
は、適切な型を持つHonoのインスタンスを作成するのに役立ちます。このメソッドをcreateFactory()
と併用すると、Env
型の定義における冗長性を回避できます。
アプリケーションがこのような場合、2つの場所でEnv
を設定する必要があります。
ts
import { createMiddleware } from 'hono/factory'
type Env = {
Variables: {
myVar: string
}
}
// 1. Set the `Env` to `new Hono()`
const app = new Hono<Env>()
// 2. Set the `Env` to `createMiddleware()`
const mw = createMiddleware<Env>(async (c, next) => {
await next()
})
app.use(mw)
createFactory()
とcreateApp()
を使用することで、Env
を1箇所だけで設定できます。
ts
import { createFactory } from 'hono/factory'
// ...
// Set the `Env` to `createFactory()`
const factory = createFactory<Env>()
const app = factory.createApp()
// factory also has `createMiddleware()`
const mw = factory.createMiddleware(async (c, next) => {
await next()
})
createFactory()
は、createApp()
によって作成されたapp
を初期化するinitApp
オプションを受け取ることができます。以下は、そのオプションを使用する例です。
ts
// factory-with-db.ts
type Env = {
Bindings: {
MY_DB: D1Database
}
Variables: {
db: DrizzleD1Database
}
}
export default createFactory<Env>({
initApp: (app) => {
app.use(async (c, next) => {
const db = drizzle(c.env.MY_DB)
c.set('db', db)
await next()
})
},
})
ts
// crud.ts
import factoryWithDB from './factory-with-db'
const app = factoryWithDB.createApp()
app.post('/posts', (c) => {
c.var.db.insert()
// ...
})