跳转到正文

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 applied

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()
  // ...
})

基于 MIT 许可证发布。