Factory ヘルパー
Factory ヘルパーは、ミドルウェアなどの 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>()オプション
optional defaultAppOptions: HonoOptions
createApp() で作成する Hono アプリケーションに渡すデフォルトのオプションです。
ts
const factory = createFactory({
defaultAppOptions: { strict: false },
})
const app = factory.createApp() // `strict: false` is appliedcreateMiddleware()
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()
// ...
})