Skip to content

팩토리 헬퍼

팩토리 헬퍼는 Hono의 미들웨어와 같은 컴포넌트를 생성하는 데 유용한 함수를 제공한다. 적절한 타입스크립트 타입을 설정하는 것이 어려울 때가 있지만, 이 헬퍼를 사용하면 쉽게 처리할 수 있다.

Import

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`가 적용됨

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. `Env`를 `new Hono()`에 설정
const app = new Hono<Env>()

// 2. `Env`를 `createMiddleware()`에 설정
const mw = createMiddleware<Env>(async (c, next) => {
  await next()
})

app.use(mw)

createFactory()createApp()을 사용하면 Env를 한 곳에서만 설정할 수 있다.

ts
import { createFactory } from 'hono/factory'

// ...

// `Env`를 `createFactory()`에 설정
const factory = createFactory<Env>()

const app = factory.createApp()

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

Released under the MIT License.