Factory Helper
Factory Helper 提供了用於建立 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
類型的定義中產生冗餘。
如果您的應用程式像這樣,您必須在兩個地方設定 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
。
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()
可以接收 initApp
選項來初始化由 createApp()
建立的 app
。以下是使用該選項的範例。
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()
// ...
})