Skip to content
Myr

feat(trie-router) : Routing with order specification (#269)

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

* Routing with order specification * fixed test * fixed for special wildcard and so on * fixed scoring * fix for `route` method

authored by Yusuke Wada · committed by GitHub · parent a18edd5 · Browse files · 9 files+227 added−60 removed
This commit

State

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

Diff stats

9 files+227 added−60 removed

  • tests:+160 added−34 removed
  • other:+67 added−26 removed

9 files+227 added−60 removed

modified:src/middleware/pretty-json/index.test.ts+10 added-6 removed
modified:src/middleware/serve-static/serve-static.test.ts+1 added-1 removed
modified:src/router/trie-router/node.test.ts+112 added-8 removed
190 unmodified lines
191})192193describe('Default with wildcard', () => {194 const node = new Node()195 node.insert('ALL', '/api/abc', 'match api')195 node.insert('ALL', '/api/*', 'fallback')196 node.insert('ALL', '/api/abc', 'match api')197 it('/api/abc', () => {198 const res = node.search('get', '/api/abc')199 expect(res).not.toBeNull()200 expect(res.handlers).toEqual(['fallback', 'match api'])
40 unmodified lines
241 })242243 describe('Blog', () => {244 const node = new Node()245 node.insert('get', '*', 'middleware a')246 node.insert('ALL', '*', 'middleware b')247 node.insert('get', '/entry', 'get entries')248 node.insert('post', '/entry/*', 'middleware c')249 node.insert('post', '/entry', 'post entry')250 node.insert('get', '/entry/:id', 'get entry')251 node.insert('get', '/entry/:id/comment/:comment_id', 'get comment')245 node.insert('get', '*', 'middleware a') // 0.1246 node.insert('ALL', '*', 'middleware b') // 0.2 <===247 node.insert('get', '/entry', 'get entries') // 1.3248 node.insert('post', '/entry/*', 'middleware c') // 1.4 <===249 node.insert('post', '/entry', 'post entry') // 1.5 <===250 node.insert('get', '/entry/:id', 'get entry') // 2.6251 node.insert('get', '/entry/:id/comment/:comment_id', 'get comment') // 4.7252 it('get /entry/123', async () => {253 const res = node.search('get', '/entry/123')254 expect(res).not.toBeNull()255 expect(res.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])
122 unmodified lines
378 node.insert('get', '/:id/:action{delete}', 'bar')379 }).not.toThrowError()380 })381})382383describe('Sort Order', () => {384 describe('Basic', () => {385 const node = new Node()386 node.insert('get', '*', 'a')387 node.insert('get', '/page', '/page')388 node.insert('get', '/:slug', '/:slug')389390 it('get /page', () => {391 const res = node.search('get', '/page')392 expect(res).not.toBeNull()393 expect(res.handlers).toEqual(['a', '/page', '/:slug'])394 })395 })396397 describe('With Named path', () => {398 const node = new Node()399 node.insert('get', '*', 'a')400 node.insert('get', '/posts/:id', '/posts/:id')401 node.insert('get', '/:type/:id', '/:type/:id')402403 it('get /posts/123', () => {404 const res = node.search('get', '/posts/123')405 expect(res).not.toBeNull()406 expect(res.handlers).toEqual(['a', '/posts/:id', '/:type/:id'])407 })408 })409410 describe('With Wildcards', () => {411 const node = new Node()412 node.insert('get', '/api/*', '1st')413 node.insert('get', '/api/*', '2nd')414 node.insert('get', '/api/posts/:id', '3rd')415 node.insert('get', '/api/*', '4th')416417 it('get /api/posts/123', () => {418 const res = node.search('get', '/api/posts/123')419 expect(res).not.toBeNull()420 expect(res.handlers).toEqual(['1st', '2nd', '4th', '3rd'])421 })422 })423424 describe('With special Wildcard', () => {425 const node = new Node()426 node.insert('get', '/posts', '/posts') // 1.1427 node.insert('get', '/posts/*', '/posts/*') // 1.2428 node.insert('get', '/posts/:id', '/posts/:id') // 2.3429430 it('get /posts', () => {431 const res = node.search('get', '/posts')432433 expect(res).not.toBeNull()434 expect(res.handlers).toEqual(['/posts', '/posts/*'])435 })436 })437438 describe('Complex', () => {439 const node = new Node()440 node.insert('get', '/api', 'x') // score 1.1441 node.insert('get', '/api/*', 'c') // score 2.2442 node.insert('get', '/api/:type', 'y') // score 2.3443 node.insert('get', '/api/:type/:id', 'd') // score 3.4444 node.insert('get', '/api/posts/:id', 'e') // score 3.5445 node.insert('get', '/api/posts/123', 'f') // score 3.6446 node.insert('get', '/*/*/:id', 'g') // score 3.7447 node.insert('get', '/api/posts/*/comment', 'z') // score 4.8 - not match448 node.insert('get', '*', 'a') // score 1.9449 node.insert('get', '*', 'b') // score 1.10450451 it('get /api/posts/123', () => {452 const res = node.search('get', '/api/posts/123')453 // ---> will match => c, d, e, e, f, g, a, b454 // ---> sort by score => a, b, c, d, e, f, g455 expect(res.handlers).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'g'])456 })457 })458459 describe('Multi match', () => {460 const node = new Node()461 node.insert('get', '*', 'GET *') // 0.1462 node.insert('get', '/abc/*', 'GET /abc/*') // 1.2463 node.insert('get', '/abc/edf', 'GET /abc/edf') // 2.3464 node.insert('get', '/abc/*/ghi/jkl', 'GET /abc/*/ghi/jkl') // 4.4465 it('get /abc/edf', () => {466 const res = node.search('get', '/abc/edf')467 expect(res).not.toBeNull()468 expect(res.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])469 })470 })471472 describe('fallback', () => {473 describe('Blog - failed', () => {474 const node = new Node()475 node.insert('post', '/entry', 'post entry') // 1.1476 node.insert('post', '/entry/*', 'fallback') // 1.2477 node.insert('get', '/entry/:id', 'get entry') // 2.3478 it('post /entry', async () => {479 const res = node.search('post', '/entry')480 expect(res).not.toBeNull()481 expect(res.handlers).toEqual(['post entry', 'fallback'])482 })483 })484 })485})
modified:src/router/trie-router/node.ts+46 added-17 removed
2 unmodified lines
3import { splitPath, getPattern } from '../../utils/url'45type Next<T> = {6 nodes: Node<T>[]7 handlers: T[]7 handlerSets: HandlerSet<T>[]8 params: Record<string, string>9}1011type HandlerSet<T> = {12 handler: T13 order: number14 name: string // For debug15}1617function findParam<T>(node: Node<T>, name: string): boolean {18 for (let i = 0, len = node.patterns.length; i < len; i++) {19 if (typeof node.patterns[i] === 'object' && node.patterns[i][1] === name) {20 return true
10 unmodified lines
31}3233export class Node<T> {34 methods: Record<string, T>[]29 handlers: T[]3536 children: Record<string, Node<T>>37 patterns: Pattern[]38 order: number = 039 name: string4041 constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {42 this.children = children || {}43 this.methods = []
5 unmodified lines
49 this.patterns = []50 }5152 insert(method: string, path: string, handler: T): Node<T> {53 this.name = `${method} ${path}`54 this.order = ++this.order5556 // eslint-disable-next-line @typescript-eslint/no-this-alias57 let curNode: Node<T> = this58 const parts = splitPath(path)59
12 unmodified lines
72 continue73 }7475 curNode.children[p] = new Node()7677 const pattern = getPattern(p)78 if (pattern) {79 if (typeof pattern === 'object') {80 for (let j = 0, len = parentPatterns.length; j < len; j++) {
7 unmodified lines
88 }89 curNode.patterns.push(pattern)90 parentPatterns.push(...curNode.patterns)91 }9293 parentPatterns.push(...curNode.patterns)94 curNode = curNode.children[p]95 }9697 const order = parts.length + this.order * 0.0198 curNode.order = order99 curNode.name = this.name100101 if (!curNode.methods.length) {102 curNode.methods = []103 }104 const m: Record<string, T> = {}105 m[method] = handler106 curNode.methods.push(m)107108 return curNode109 }11092 private getHandlers(node: Node<T>, method: string): T[] {93 const handlers: T[] = []111 private getHandlerSets(node: Node<T>, method: string): HandlerSet<T>[] {112 const handlerSets: HandlerSet<T>[] = []113 node.methods.map((m) => {114 let handler = m[method]115 if (handler !== undefined) {97 handlers.push(handler)116 handlerSets.push({ handler: handler, order: node.order, name: node.name })117 return118 }119 handler = m[METHOD_NAME_ALL]120 if (handler !== undefined) {102 handlers.push(handler)121 handlerSets.push({ handler: handler, order: node.order, name: node.name })122 return123 }124 })125107 return handlers126 return handlerSets127 }128129 private next(node: Node<T>, part: string, method: string, isLast: boolean): Next<T> {111 const handlers: T[] = []130 const handlerSets: HandlerSet<T>[] = []131 const nextNodes: Node<T>[] = []132 const params: Record<string, string> = {}133134 for (let j = 0, len = node.patterns.length; j < len; j++) {
3 unmodified lines
138 // '/hello/*/foo' => match /hello/bar/foo139 if (pattern === '*') {140 const astNode = node.children['*']141 if (astNode) {123 handlers.push(...this.getHandlers(astNode, method))142 handlerSets.push(...this.getHandlerSets(astNode, method))143 nextNodes.push(astNode)144 }145 }146
4 unmodified lines
151 const [key, name, matcher] = pattern152 if (matcher === true || (matcher instanceof RegExp && matcher.test(part))) {153 if (typeof key === 'string') {154 if (isLast === true) {136 handlers.push(...this.getHandlers(node.children[key], method))155 handlerSets.push(...this.getHandlerSets(node.children[key], method))156 }157 nextNodes.push(node.children[key])158 }159 if (typeof name === 'string') {
5 unmodified lines
165 const nextNode = node.children[part]166 if (nextNode) {167 if (isLast === true) {168 // '/hello/*' => match '/hello'150 if (nextNode.children['*'] !== undefined) {151 handlers.push(...this.getHandlers(nextNode.children['*'], method))169 if (nextNode.children['*']) {170 const astNode = nextNode.children['*']171 astNode.order = --astNode.order172 handlerSets.push(...this.getHandlerSets(astNode, method))173 }153 handlers.push(...this.getHandlers(nextNode, method))174 handlerSets.push(...this.getHandlerSets(nextNode, method))175 }176 nextNodes.push(nextNode)177 }178179 const next: Next<T> = {180 nodes: nextNodes,160 handlers: handlers,181 handlerSets: handlerSets,182 params: params,183 }184 return next185 }186187 search(method: string, path: string): Result<T> {167 const handlers: T[] = []188 const handlerSets: HandlerSet<T>[] = []189 let params: Record<string, string> = {}190191 // eslint-disable-next-line @typescript-eslint/no-this-alias192 const curNode: Node<T> = this
9 unmodified lines
202 const res = this.next(curNodes[j], p, method, isLast)203 if (res.nodes.length === 0) {204 continue205 }185 handlers.push(...res.handlers)206 handlerSets.push(...res.handlerSets)207 params = Object.assign(params, res.params)208 tempNodes.push(...res.nodes)209 }210211 curNodes = tempNodes212 }213193 if (handlers.length <= 0) return null214 if (handlerSets.length <= 0) return null215216 const handlers = handlerSets217 .sort((a, b) => {218 return a.order - b.order219 })220 .map((s) => {221 return s.handler222 })223224 return new Result<T>(handlers, params)225 }226}
modified:src/router/trie-router/router.test.ts+14 added-1 removed
40 unmodified lines
41 expect(res.handlers).toEqual(['get wildcard'])42 })4344 it('Default', async () => {45 router.add('GET', '/api/abc', 'get api')45 router.add('GET', '/api/*', 'fallback')46 router.add('GET', '/api/abc', 'get api')47 let res = router.match('GET', '/api/abc')48 expect(res).not.toBeNull()49 expect(res.handlers).toEqual(['fallback', 'get api'])50 res = router.match('GET', '/api/def')
55 unmodified lines
106 expect(res.handlers).toEqual(['middleware a'])107 })108 })109})110111describe('Fallback', () => {112 const router = new TrieRouter<string>()113114 router.add('POST', '/entry', 'post entry')115 router.add('POST', '/entry/*', 'fallback')116 router.add('GET', '/entry/:id', 'get entry')117 it('POST /entry', async () => {118 const res = router.match('POST', '/entry')119 expect(res).not.toBeNull()120 expect(res.handlers).toEqual(['post entry', 'fallback'])121 })122})
modified:src/compose.test.ts+1 added-1 removed
162 unmodified lines
163 await next()164 c.res = new Response('Not authorized', { status: 401 })165 }166167 middleware.push(handler)167 middleware.push(mHandler)168 middleware.push(handler)169170 it('Should return 401 Response', async () => {171 const composed = compose<Context>(middleware, onError)172 const context = await composed(c)
464 unmodified lines
modified:src/compose.ts-1 removed
30 unmodified lines
31 // If handler return Response like `return c.text('foo')`32 if (res && context instanceof Context) {33 context.res = res34 context.res.finalized = true35 await dispatch(i + 1) // <--- Call next()35 }36 return context37 })38 .catch((err) => {
13 unmodified lines
modified:src/hono.test.ts+22 added-17 removed
596 unmodified lines
597 describe('Basic', () => {598 const app = new Hono()599 const api = new Hono()600 const middleware = new Hono()601 api.get('/posts', (c) => c.text('List'))602 api.post('/posts', (c) => c.text('Create'))603 api.get('/posts/:id', (c) => c.text(`GET ${c.req.param('id')}`))601602 api.use('*', async (c, next) => {603 await next()604 c.res.headers.append('x-custom-a', 'a')605 })606607 api.get('/posts', (c) => c.text('List'))608 api.post('/posts', (c) => c.text('Create'))609 api.get('/posts/:id', (c) => c.text(`GET ${c.req.param('id')}`))610 app.route('/api', api)611612 app.get('/foo', (c) => c.text('bar'))613
112 unmodified lines
726727describe('Multiple handler', () => {728 describe('handler + handler', () => {729 const app = new Hono()728 app.get('/:type/:id', (c) => {729 c.status(404)730 c.header('foo', 'bar')731 return c.text('foo')732 })730731 app.get('/posts/:id', (c) => {732 const id = c.req.param('id')735 c.header('foo2', 'bar2')733 c.header('foo', 'bar')734 return c.text(`id is ${id}`)735 })736737 app.get('/:type/:id', (c) => {738 c.status(404)739 c.header('foo2', 'bar2')740 return c.text('foo')741 })742 it('Should return response from `specialized` route', async () => {743 const res = await app.request('http://localhost/posts/123')744 expect(res.status).toBe(200)745 expect(await res.text()).toBe('id is 123')742 expect(res.headers.get('foo')).toBeNull()743 expect(res.headers.get('foo2')).toBe('bar2')746 expect(res.headers.get('foo')).toBe('bar')747 expect(res.headers.get('foo2')).toBeNull()748 })749 })750751 describe('Duplicate param name', () => {
63 unmodified lines
815816describe('Multiple handler - async', () => {817 describe('handler + handler', () => {818 const app = new Hono()815 app.get('/:type/:id', async (c) => {816 await new Promise((resolve) => setTimeout(resolve, 1))817 c.header('foo', 'bar')818 c.status(404)819 return c.text('foo')820 })819 app.get('/posts/:id', async (c) => {820 await new Promise((resolve) => setTimeout(resolve, 1))821 c.header('foo2', 'bar2')822 const id = c.req.param('id')823 return c.text(`id is ${id}`)824 })825 app.get('/:type/:id', async (c) => {826 await new Promise((resolve) => setTimeout(resolve, 1))827 c.header('foo', 'bar')828 c.status(404)829 return c.text('foo')830 })831832 it('Should return response from `specialized` route', async () => {833 const res = await app.request('http://localhost/posts/123')834 expect(res.status).toBe(200)835 expect(await res.text()).toBe('id is 123')
5 unmodified lines
modified:src/hono.ts+21 added-8 removed
79 unmodified lines
80interface Route<E extends Env> {81 path: string82 method: string83 handler: Handler<string, E>84 order: number85}8687export class Hono<E = Env, P extends string = '/'> extends defineDynamicClass()<E, P, Hono<E, P>> {88 readonly routerClass: { new (): Router<any> } = TrieRouter
10 unmodified lines
99 super()100101 const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]102 allMethods.map((method) => {102 this[method] = <Path extends string>(103 this[method] = <Path extends string = ''>(104 args1: Path | Handler<ParamKeys<Path>, E>,105 ...args: [Handler<ParamKeys<Path>, E>]106 ) => {107 if (typeof args1 === 'string') {
30 unmodified lines
138 return c.text(message, 500)139 }140141 route(path: string, app?: Hono<any>): Hono<E, P> {141 this._tempPath = path142 if (app) {143 app.routes.map((r) => {144 this.addRoute(r.method, r.path, r.handler)145 })146 this._tempPath = null142 if (!app) {143 this._tempPath = path144 return this145 }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 })161162 return this163 }164165 use(path: string, ...middleware: Handler<string, E>[]): Hono<E, P>
25 unmodified lines
191 if (this._tempPath) {192 path = mergePath(this._tempPath, path)193 }194 this._router.add(method, path, handler)182 const r: Route<E> = { path: path, method: method, handler: handler }195 const r: Route<E> = { path: path, method: method, handler: handler, order: this.routes.length }196 this.routes.push(r)197 }198199 private async matchRoute(method: string, path: string): Promise<Result<Handler<string, E>>> {
60 unmodified lines