Skip to content

RPC 的分组路由

🌐 Grouping routes for RPC

如果你想正确地为多个 app 启用类型推断,你可以按如下方式使用 app.route()

🌐 If you want to enable type inference for multiple apps correctly, you can use app.route() as follows.

将像 app.get()app.post() 这样的方法返回的值传递给 app.route() 的第二个参数。

🌐 Pass the value returned from methods like app.get() or app.post() to the second argument of app.route().

ts
import { Hono } from 'hono'
import { hc } from 'hono/client'

const authorsApp = new Hono()
  .get('/', (c) => c.json({ result: 'list authors' }))
  .post('/', (c) => c.json({ result: 'create an author' }, 201))
  .get('/:id', (c) => c.json({ result: `get ${c.req.param('id')}` }))

const booksApp = new Hono()
  .get('/', (c) => c.json({ result: 'list books' }))
  .post('/', (c) => c.json({ result: 'create a book' }, 201))
  .get('/:id', (c) => c.json({ result: `get ${c.req.param('id')}` }))

const app = new Hono()
  .route('/authors', authorsApp)
  .route('/books', booksApp)

type AppType = typeof app

另请参阅

🌐 See also

Hono 中文网 - 粤ICP备13048890号