Best way to manage and mount routes in a DRY way #1836
Answered
by
yusukebe
jamiehaywood
asked this question in
Q&A
-
I'm looking at creating a // routes.ts
import { MiddlewareHandler, Hono, Context } from "hono";
import { METHODS } from "hono/dist/types/router";
type Methods = (typeof METHODS)[number];
interface Routes {
path: string;
method: Pick<Hono, Methods> extends string ? Pick<Hono, Methods> : Methods;
middlewares: MiddlewareHandler[];
}
const routes: Routes[] = [
{
path: "/bar",
method: "get",
middlewares: [async (c: Context) => c.json({ bar: "bar" })],
},
{
path: "/foo",
method: "get" as const,
middlewares: [async (c: Context) => c.json({ foo: "foo" })],
},
]; and consuming in my // index.ts
const app = new Hono();
routes.map((route) => app[route.method](route.path, ...route.middlewares));
... Do you think this is a good way to cleanly organise and mount the middlewares? |
Beta Was this translation helpful? Give feedback.
Answered by
yusukebe
Dec 21, 2023
Replies: 2 comments 6 replies
-
As a separate point - are there any plans to consolidate the types into a single exported file, so we can avoid importing from |
Beta Was this translation helpful? Give feedback.
3 replies
-
This code is best: import { MiddlewareHandler, Handler, Hono } from 'hono'
import { createFactory } from 'hono/factory'
type Methods = ['get', 'post', 'put', 'delete', 'options', 'patch'][number]
interface Routes {
path: string
method: Methods
handlers: (Handler | MiddlewareHandler)[]
}
const factory = createFactory()
const routes: Routes[] = [
{
path: '/bar',
method: 'get',
handlers: factory.createHandlers((c) => c.json({ bar: 'bar' }))
},
{
path: '/foo',
method: 'get' as const,
handlers: factory.createHandlers((c) => c.json({ foo: 'foo' }))
}
]
const app = new Hono()
routes.map((route) => app.on(route.method, route.path, ...route.handlers))
export default app |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
jamiehaywood
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code is best: