Skip to content
Myr

fix(router): fixed trie-router bugs (#271)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Yusuke Wada · committed by GitHub · parent 7cc9644 · Browse files · 3 files+75 added−51 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+75 added−51 removed

  • tests:+28 added−0 removed
  • other:+47 added−51 removed

3 files+75 added−51 removed

modified:src/router/trie-router/node.test.ts+28 added
467 unmodified lines
468 expect(res.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])469 })470 })471472 describe('Multi match', () => {473 const node = new Node()474475 node.insert('get', '/api/*', 'a') // 1.1476 node.insert('get', '/api/entry', 'entry') // 2.2477 node.insert('ALL', '/api/*', 'b') // 1.2478479 it('get /api/entry', async () => {480 const res = node.search('get', '/api/entry')481 expect(res).not.toBeNull()482 expect(res.handlers).toEqual(['a', 'b', 'entry'])483 })484 })485486 describe('fallback', () => {487 describe('Blog - failed', () => {488 const node = new Node()489 node.insert('post', '/entry', 'post entry') // 1.1
6 unmodified lines
496 })497 })498 })499})500501describe('Multi match', () => {502 const node = new Node()503504 node.insert('get', '/api/*', 'a') // 1.1505 node.insert('get', '/api/entry', 'entry') // 2.2506 node.insert('ALL', '/api/*', 'b') // 1.2507508 it('get /api/entry', async () => {509 const res = node.search('get', '/api/entry')510 expect(res).not.toBeNull()511 expect(res.handlers).toEqual(['a', 'b', 'entry'])512 })513})
modified:src/router/trie-router/node.ts+36 added-25 removed
1import { Result, METHOD_NAME_ALL } from '../../router'1import type { Result } from '../../router'2import { METHOD_NAME_ALL } from '../../router'3import type { Pattern } from '../../utils/url'4import { splitPath, getPattern } from '../../utils/url'56type Next<T> = {
3 unmodified lines
10}1112type HandlerSet<T> = {13 handler: T13 order: number14 score: number15 name: string // For debug16}1718function findParam<T>(node: Node<T>, name: string): boolean {
12 unmodified lines
31 return false32}3334export class Node<T> {34 methods: Record<string, T>[]35 methods: Record<string, HandlerSet<T>>[]3637 children: Record<string, Node<T>>38 patterns: Pattern[]39 order: number = 0
2 unmodified lines
42 constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {43 this.children = children || {}44 this.methods = []45 if (method && handler) {45 const m: Record<string, T> = {}46 m[method] = handler46 const m: Record<string, HandlerSet<T>> = {}47 m[method] = { handler: handler, score: 0, name: this.name }48 this.methods = [m]49 }50 this.patterns = []51 }
42 unmodified lines
94 parentPatterns.push(...curNode.patterns)95 curNode = curNode.children[p]96 }9797 const order = parts.length + this.order * 0.0198 curNode.order = order99 curNode.name = this.name98 let score = 199100 if (path === '*') {101 score = score + this.order * 0.01102 } else {103 score = parts.length + 1 + this.order * 0.01104 }105106 if (!curNode.methods.length) {107 curNode.methods = []108 }104 const m: Record<string, T> = {}105 m[method] = handler109110 const m: Record<string, HandlerSet<T>> = {}111112 const handlerSet: HandlerSet<T> = { handler: handler, name: this.name, score: score }113114 m[method] = handlerSet115 curNode.methods.push(m)116117 return curNode118 }119111 private getHandlerSets(node: Node<T>, method: string): HandlerSet<T>[] {120 private getHandlerSets(node: Node<T>, method: string, wildcard?: boolean): HandlerSet<T>[] {121 const handlerSets: HandlerSet<T>[] = []122 node.methods.map((m) => {114 let handler = m[method]115 if (handler !== undefined) {116 handlerSets.push({ handler: handler, order: node.order, name: node.name })123 const handlerSet = m[method] || m[METHOD_NAME_ALL]124 if (handlerSet !== undefined) {125 const hs = { ...handlerSet }126 if (wildcard) {127 hs.score = handlerSet.score - 1128 }129 handlerSets.push(hs)130 return131 }119 handler = m[METHOD_NAME_ALL]120 if (handler !== undefined) {121 handlerSets.push({ handler: handler, order: node.order, name: node.name })122 return123 }132 })133134 return handlerSets135 }
10 unmodified lines
146 // '/hello/*/foo' => match /hello/bar/foo147 if (pattern === '*') {148 const astNode = node.children['*']149 if (astNode) {150 let wildcard = false151 if (!Object.keys(astNode.children).length) {152 wildcard = true153 }142 handlerSets.push(...this.getHandlerSets(astNode, method))154 handlerSets.push(...this.getHandlerSets(astNode, method, wildcard))155 nextNodes.push(astNode)156 }157 }158
15 unmodified lines
174 }175 }176177 const nextNode = node.children[part]178179 if (nextNode) {180 if (isLast === true) {181 // '/hello/*' => match '/hello'182 if (nextNode.children['*']) {170 const astNode = nextNode.children['*']171 astNode.order = --astNode.order172 handlerSets.push(...this.getHandlerSets(astNode, method))183 handlerSets.push(...this.getHandlerSets(nextNode.children['*'], method, true))184 }185 handlerSets.push(...this.getHandlerSets(nextNode, method))186 }187 nextNodes.push(nextNode)
37 unmodified lines
225 if (handlerSets.length <= 0) return null226227 const handlers = handlerSets228 .sort((a, b) => {218 return a.order - b.order229 return a.score - b.score230 })231 .map((s) => {232 return s.handler233 })234224 return new Result<T>(handlers, params)235 return { handlers, params }236 }237}
modified:src/hono.ts+11 added-26 removed
79 unmodified lines
80interface Route<E extends Env> {81 path: string82 method: string83 handler: Handler<string, E>84 order: number84}8586export class Hono<E = Env, P extends string = '/'> extends defineDynamicClass()<E, P, Hono<E, P>> {88 readonly routerClass: { new (): Router<any> } = TrieRouter87 readonly router: Router<Handler<string, E>> = new TrieRouter()88 readonly strict: boolean = true // strict routing - default is true90 private _router: Router<Handler<string, E>>89 private _tempPath: string90 private path: string = '/'9192 private _cacheResponse: Response9394 routes: Route<E>[] = []9598 constructor(init: Partial<Pick<Hono, 'routerClass' | 'strict'>> = {}) {96 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {97 super()9899 const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]100 allMethods.map((method) => {
16 unmodified lines
117 })118119 Object.assign(this, init)120123 this._router = new this.routerClass()121 this._tempPath = null122123 this._cacheResponse = new Response(null, { status: 404 })124 this._cacheResponse.finalized = false
10 unmodified lines
135 return c.text(message, 500)136 }137138 route(path: string, app?: Hono<any>): Hono<E, P> {142 if (!app) {143 this._tempPath = path144 return this139 this._tempPath = path140 if (app) {141 app.routes.map((r) => {142 this.addRoute(r.method, r.path, r.handler)143 })144 this._tempPath = null145 }146147 app.routes.map((r) => {148 r.path = mergePath(path, r.path)149 })150 const routes = [...this.routes, ...app.routes]151 this._router = new this.routerClass()152153 routes154 .sort((a, b) => {155 return a.order - b.order156 })157 .map((r) => {158 const path = r.path159 this.addRoute(r.method, path, r.handler)160 })161147 return this148 }149150 use(path: string, ...middleware: Handler<string, E>[]): Hono<E, P>
24 unmodified lines
175 method = method.toUpperCase()176 if (this._tempPath) {177 path = mergePath(this._tempPath, path)178 }194 this._router.add(method, path, handler)195 const r: Route<E> = { path: path, method: method, handler: handler, order: this.routes.length }179 this.router.add(method, path, handler)180 const r: Route<E> = { path: path, method: method, handler: handler }181 this.routes.push(r)182 }183184 private async matchRoute(method: string, path: string): Promise<Result<Handler<string, E>>> {200 return this._router.match(method, path)185 return this.router.match(method, path)186 }187188 private async dispatch(request: Request, event?: FetchEvent, env?: E): Promise<Response> {189 const path = getPathFromURL(request.url, { strict: this.strict })
55 unmodified lines