H
Hono4w ago
meow

Abstracted routes but with context and types

I know there's some discussion of abstracted routes under https://hono.dev/docs/guides/best-practices. But there's no example which preserves the types from the context or middleware.
import hello from "./hello.ts"

type Env = {Variables: { db: typeof db }}

const factory = createFactory<Env>({
initApp: (app) => {
app.use(async (ctx, next) => {
ctx.set("db", db)
await next()
})
},
})

export const app = factory.createApp()

app.route("hello", hello)
import hello from "./hello.ts"

type Env = {Variables: { db: typeof db }}

const factory = createFactory<Env>({
initApp: (app) => {
app.use(async (ctx, next) => {
ctx.set("db", db)
await next()
})
},
})

export const app = factory.createApp()

app.route("hello", hello)
How should I construct hello.ts so that the subroutes all have access to db in the context?
2 Replies
Aditya Mathur
Aditya Mathur4w ago
You can use the same factory to create the app in hello.ts. So first abstract the createFactory logic in a separate file and use it's createApp function to create app for the both the routers
meow
meowOP3w ago
Super thanks.

Did you find this page helpful?