Skip to content

Best way to manage and mount routes in a DRY way #1836

Answered by yusukebe
jamiehaywood asked this question in Q&A
Discussion options

You must be logged in to vote

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))

ex…

Replies: 2 comments 6 replies

Comment options

You must be logged in to vote
3 replies
@yusukebe
Comment options

@jamiehaywood
Comment options

@yusukebe
Comment options

Comment options

You must be logged in to vote
3 replies
@jamiehaywood
Comment options

@yusukebe
Comment options

@jamiehaywood
Comment options

Answer selected by jamiehaywood
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants