Skip to content

Commit

Permalink
feat(factory): Allow HonoOptions<E> with factory
Browse files Browse the repository at this point in the history
  • Loading branch information
miyaji255 committed Dec 31, 2024
1 parent 1e62912 commit 89e8add
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
16 changes: 16 additions & 0 deletions src/helper/factory/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,22 @@ describe('createApp', () => {
expect(res.status).toBe(200)
expect(await res.text()).toBe('bar')
})

it('Should use the default options', async () => {
const app = createFactory({ defaultOptions: { strict: false } }).createApp()
app.get('/hello', (c) => c.text('hello'))
const res = await app.request('/hello/')
expect(res.status).toBe(200)
expect(await res.text()).toBe('hello')
})

it('Should override the default options when creating', async () => {
const app = createFactory({ defaultOptions: { strict: true } }).createApp({ strict: false })
app.get('/hello', (c) => c.text('hello'))
const res = await app.request('/hello/')
expect(res.status).toBe(200)
expect(await res.text()).toBe('hello')
})
})

describe('Lint rules', () => {
Expand Down
14 changes: 11 additions & 3 deletions src/helper/factory/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

/* eslint-disable @typescript-eslint/no-explicit-any */
import { Hono } from '../../hono'
import type { HonoOptions } from '../../hono-base'
import type {
Env,
H,
Expand Down Expand Up @@ -285,13 +286,19 @@ export interface CreateHandlersInterface<E extends Env, P extends string> {

export class Factory<E extends Env = any, P extends string = any> {
private initApp?: InitApp<E>
#defaultOptions?: HonoOptions<E>

constructor(init?: { initApp?: InitApp<E> }) {
constructor(init?: { initApp?: InitApp<E>; defaultOptions?: HonoOptions<E> }) {
this.initApp = init?.initApp
this.#defaultOptions = init?.defaultOptions
}

createApp = (): Hono<E> => {
const app = new Hono<E>()
createApp = (options?: HonoOptions<E>): Hono<E> => {
const app = new Hono<E>(
options && this.#defaultOptions
? { ...this.#defaultOptions, ...options }
: options ?? this.#defaultOptions
)
if (this.initApp) {
this.initApp(app)
}
Expand All @@ -308,6 +315,7 @@ export class Factory<E extends Env = any, P extends string = any> {

export const createFactory = <E extends Env = any, P extends string = any>(init?: {
initApp?: InitApp<E>
defaultOptions?: HonoOptions<E>
}): Factory<E, P> => new Factory<E, P>(init)

export const createMiddleware = <
Expand Down

0 comments on commit 89e8add

Please sign in to comment.