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
Provenance
- Commit
ef65308- Tree
0dfb90a- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
7cc9644
3 files changed+75 added−51 removed
modified:src/router/trie-router/node.test.ts+28 added
467 unmodified lines468 expect(res.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])469 })470 })471 472+ describe('Multi match', () => {473+ const node = new Node()474+475+ node.insert('get', '/api/*', 'a') // 1.1476+ node.insert('get', '/api/entry', 'entry') // 2.2477+ node.insert('ALL', '/api/*', 'b') // 1.2478+479+ 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+ })485+486 describe('fallback', () => {487 describe('Blog - failed', () => {488 const node = new Node()489 node.insert('post', '/entry', 'post entry') // 1.16 unmodified lines496 })497 })498 })499 })500+501+describe('Multi match', () => {502+ const node = new Node()503+504+ node.insert('get', '/api/*', 'a') // 1.1505+ node.insert('get', '/api/entry', 'entry') // 2.2506+ node.insert('ALL', '/api/*', 'b') // 1.2507+508+ 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
1-import { Result, METHOD_NAME_ALL } from '../../router'1+import type { Result } from '../../router'2+import { METHOD_NAME_ALL } from '../../router'3 import type { Pattern } from '../../utils/url'4 import { splitPath, getPattern } from '../../utils/url'5 6 type Next<T> = {3 unmodified lines10 }11 12 type HandlerSet<T> = {13 handler: T13- order: number14+ score: number15 name: string // For debug16 }17 18 function findParam<T>(node: Node<T>, name: string): boolean {12 unmodified lines31 return false32 }33 34 export class Node<T> {34- methods: Record<string, T>[]35+ methods: Record<string, HandlerSet<T>>[]36 37 children: Record<string, Node<T>>38 patterns: Pattern[]39 order: number = 02 unmodified lines42 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 lines94 parentPatterns.push(...curNode.patterns)95 curNode = curNode.children[p]96 }97 97- const order = parts.length + this.order * 0.0198- curNode.order = order99- curNode.name = this.name98+ let score = 199 100+ if (path === '*') {101+ score = score + this.order * 0.01102+ } else {103+ score = parts.length + 1 + this.order * 0.01104+ }105+106 if (!curNode.methods.length) {107 curNode.methods = []108 }104- const m: Record<string, T> = {}105- m[method] = handler109+110+ const m: Record<string, HandlerSet<T>> = {}111+112+ const handlerSet: HandlerSet<T> = { handler: handler, name: this.name, score: score }113+114+ m[method] = handlerSet115 curNode.methods.push(m)116 117 return curNode118 }119 111- 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 })133 134 return handlerSets135 }10 unmodified lines146 // '/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 lines174 }175 }176 177 const nextNode = node.children[part]178+179 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 lines225 if (handlerSets.length <= 0) return null226 227 const handlers = handlerSets228 .sort((a, b) => {218- return a.order - b.order229+ return a.score - b.score230 })231 .map((s) => {232 return s.handler233 })234 224- return new Result<T>(handlers, params)235+ return { handlers, params }236 }237 }modified:src/hono.ts+11 added-26 removed
79 unmodified lines80 interface Route<E extends Env> {81 path: string82 method: string83 handler: Handler<string, E>84- order: number84 }85 86 export 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 = '/'91 92 private _cacheResponse: Response93 94 routes: Route<E>[] = []95 98- constructor(init: Partial<Pick<Hono, 'routerClass' | 'strict'>> = {}) {96+ constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {97 super()98 99 const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]100 allMethods.map((method) => {16 unmodified lines117 })118 119 Object.assign(this, init)120 123- this._router = new this.routerClass()121 this._tempPath = null122 123 this._cacheResponse = new Response(null, { status: 404 })124 this._cacheResponse.finalized = false10 unmodified lines135 return c.text(message, 500)136 }137 138 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 }146 147- 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()152-153- 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- })161-147 return this148 }149 150 use(path: string, ...middleware: Handler<string, E>[]): Hono<E, P>24 unmodified lines175 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 }183 184 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 }187 188 private async dispatch(request: Request, event?: FetchEvent, env?: E): Promise<Response> {189 const path = getPathFromURL(request.url, { strict: this.strict })55 unmodified lines