Skip to content

Route 助手

Route 助手提供更丰富的路由信息,便于调试与中间件开发。它可以访问匹配到的路由列表以及当前正在处理的路由。

导入

ts
import { Hono } from 'hono'
import {
  matchedRoutes,
  routePath,
  baseRoutePath,
  basePath,
} from 'hono/route'

用法

基本路由信息

ts
const app = new Hono()

app.get('/posts/:id', (c) => {
  const currentPath = routePath(c) // '/posts/:id'
  const routes = matchedRoutes(c) // 匹配到的路由数组

  return c.json({
    path: currentPath,
    totalRoutes: routes.length,
  })
})

搭配子应用

ts
const app = new Hono()
const apiApp = new Hono()

apiApp.get('/posts/:id', (c) => {
  return c.json({
    routePath: routePath(c), // '/posts/:id'
    baseRoutePath: baseRoutePath(c), // '/api'
    basePath: basePath(c), // '/api'(包含实际参数)
  })
})

app.route('/api', apiApp)

matchedRoutes()

返回一个数组,其中包含当前请求匹配到的所有路由(包括中间件)。

ts
app.all('/api/*', (c, next) => {
  console.log('API middleware')
  return next()
})

app.get('/api/users/:id', (c) => {
  const routes = matchedRoutes(c)
  // 返回:[
  //   { method: 'ALL', path: '/api/*', handler: [Function] },
  //   { method: 'GET', path: '/api/users/:id', handler: [Function] }
  // ]
  return c.json({ routes: routes.length })
})

routePath()

返回当前处理器注册的路由路径模式。

ts
app.get('/posts/:id', (c) => {
  console.log(routePath(c)) // '/posts/:id'
  return c.text('Post details')
})

搭配索引参数

可以传入一个索引,获取指定位置的路由路径,行为类似 Array.prototype.at()

ts
app.all('/api/*', (c, next) => {
  return next()
})

app.get('/api/users/:id', (c) => {
  console.log(routePath(c, 0)) // '/api/*'(第一个匹配的路由)
  console.log(routePath(c, -1)) // '/api/users/:id'(最后一个匹配的路由)
  return c.text('User details')
})

baseRoutePath()

返回路由定义时指定的基础路径模式。

ts
const subApp = new Hono()
subApp.get('/posts/:id', (c) => {
  return c.text(baseRoutePath(c)) // '/:sub'
})

app.route('/:sub', subApp)

搭配索引参数

同样可以传入索引以获取特定位置的基础路由路径,行为类似 Array.prototype.at()

ts
app.all('/api/*', (c, next) => {
  return next()
})

const subApp = new Hono()
subApp.get('/users/:id', (c) => {
  console.log(baseRoutePath(c, 0)) // '/'(第一个匹配的路由)
  console.log(baseRoutePath(c, -1)) // '/api'(最后一个匹配的路由)
  return c.text('User details')
})

app.route('/api', subApp)

basePath()

返回当前请求实际访问的基础路径(包含解析后的参数)。

ts
const subApp = new Hono()
subApp.get('/posts/:id', (c) => {
  return c.text(basePath(c)) // '/api'(例如请求 '/api/posts/123')
})

app.route('/:sub', subApp)

Released under the MIT License.