index.ts
This file
Path
src/helper/dev/index.ts
79 lines · 2.2 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–79why, one step back1/**2 * @module3 * Dev Helper for Hono.4 */56import type { Hono } from '../../hono'7import type { Env, RouterRoute } from '../../types'8import { getColorEnabled } from '../../utils/color'9import { findTargetHandler, isMiddleware } from '../../utils/handler'1011interface ShowRoutesOptions {12 verbose?: boolean13 colorize?: boolean14}1516interface RouteData {17 path: string18 method: string19 name: string20 isMiddleware: boolean21}2223const handlerName = (handler: Function): string => {24 return handler.name || (isMiddleware(handler) ? '[middleware]' : '[handler]')25}2627export const inspectRoutes = <E extends Env>(hono: Hono<E>): RouteData[] => {28 return hono.routes.map(({ path, method, handler }: RouterRoute) => {29 const targetHandler = findTargetHandler(handler)30 return {31 path,32 method,33 name: handlerName(targetHandler),34 isMiddleware: isMiddleware(targetHandler),35 }36 })37}3839export const showRoutes = <E extends Env>(hono: Hono<E>, opts?: ShowRoutesOptions): void => {40 const colorEnabled = opts?.colorize ?? getColorEnabled()41 const routeData: Record<string, RouteData[]> = {}42 let maxMethodLength = 043 let maxPathLength = 04445 inspectRoutes(hono)46 .filter(({ isMiddleware }) => opts?.verbose || !isMiddleware)47 .map((route) => {48 const key = `${route.method}-${route.path}`49 ;(routeData[key] ||= []).push(route)50 if (routeData[key].length > 1) {51 return52 }53 maxMethodLength = Math.max(maxMethodLength, route.method.length)54 maxPathLength = Math.max(maxPathLength, route.path.length)55 return { method: route.method, path: route.path, routes: routeData[key] }56 })57 .forEach((data) => {58 if (!data) {59 return60 }61 const { method, path, routes } = data6263 const methodStr = colorEnabled ? `\x1b[32m${method}\x1b[0m` : method64 console.log(`${methodStr} ${' '.repeat(maxMethodLength - method.length)} ${path}`)6566 if (!opts?.verbose) {67 return68 }6970 routes.forEach(({ name }) => {71 console.log(`${' '.repeat(maxMethodLength + 3)} ${name}`)72 })73 })74}7576export const getRouterName = <E extends Env>(app: Hono<E>): string => {77 app.router.match('GET', '/')78 return app.router.name79}