Define routes as an object literal
What is the feature you are proposing?
Hey!
Is it somehow possible to define my routes as an object literal, where each key is the route path and values are Hono instances?
E.g:
import { Hono } from "hono";
const foo = new Hono().get(async (c) => c.jsonT("foo"));
const bar = new Hono().get(async (c) => c.jsonT("bar"));
// this is currently what I have to do:
const router = new Hono()
.route("/foo", foo)
.route("/bar", bar);
// this is what I want:
const router = new Hono().routes({ companies, contacts });
I was trying to come up with a util that would walk over the object and add every route with .route, but wouldn't make it work while preserving all types.
Any ideas? Thanks!
Hi @dodas,
Currently, no. I understand your desire for this feature, but I believe adding an additional API app.routes() is not a so good idea. The Hono core should be kept small. But it's my current opinion.
Hey @yusukebe!
I agree that this is probably not something that should be added to the core. Would it be currently possible to write such util in user-land? e.g.
import { Hono } from "hono";
const foo = new Hono().get(async (c) => c.jsonT("foo"));
const bar = new Hono().get(async (c) => c.jsonT("bar"));
const routes = { foo, bar };
// could mergeRoutes be implemented in user-land, or in an external package?
const app = mergeRoutes(new Hono(), routes);
Yeah, you can do it but there are some points to consider.
One of the points is how to map the object and path. You might write it as follows, but it's up to you.
const routes = {
'/foo': foo,
'/bar': bar
}
And one more thing is about types. I haven't tried it, but it might not be able to infer types correctly.
Anyway, it's worth trying.