Introduce StaticRouter and SmartRouter (#501)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* refactor(router): Export supported HTTP methods. * refactor(router): Introduce UnsupportedPathError. * feat(static-router): Introduce StaticRouter. * feat(reg-exp-router): Add "allowAmbiguous" option to RegExpRouter. * feat(smart-router): Introduce SmartRouter. * feat(hono): Make SmartRouter the default router. * chore: denoify * refactor(smart-router): routers is never undefined. * chore: denoify * refactor: Fix test for SmartRouter.
authored by Taku Amano · committed by GitHub · parent 3697e15 · Browse files · 17 files·+563 added−35 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
17 files+563 added−35 removed
- tests:+223 added−23 removed
- other:+340 added−12 removed
Provenance
- Commit
a149ddd- Tree
3c7122d- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
3697e15
17 files changed+563 added−35 removed
modified:deno_dist/router/reg-exp-router/router.ts+9 added-1 removed
1 /* eslint-disable @typescript-eslint/ban-ts-comment */2 import type { Router, Result } from '../../router.ts'3-import { METHOD_NAME_ALL } from '../../router.ts'3+import { METHOD_NAME_ALL, UnsupportedPathError } from '../../router.ts'4 import type { ParamMap } from './trie.ts'5 import { Trie } from './trie.ts'6 7 interface Hint {191 unmodified lines199 return true200 }201 202 export class RegExpRouter<T> implements Router<T> {203+ allowAmbiguous: boolean = true204 routeData?: {205 index: number206 routes: Route<T>[]207 methods: Set<string>208 } = { index: 0, routes: [], methods: new Set() }209 210+ constructor(init: Partial<Pick<RegExpRouter<T>, 'allowAmbiguous'>> = {}) {211+ Object.assign(this, init)212+ }213+214 add(method: string, path: string, handler: T) {215 if (!this.routeData) {216 throw new Error('Can not add a route since the matcher is already built.')217 }224 unmodified lines442 }443 444 routes[i].hint.maybeHandler = false445 } else if (compareResult === 2) {446+ if (!this.allowAmbiguous) {447+ throw new UnsupportedPathError(routes[i].path)448+ }449 // ambiguous450 hasAmbiguous = true451 452 if (!verifyDuplicateParam([routes[i], routes[j]])) {30 unmodified linesadded:deno_dist/router/smart-router/index.ts+1 added
1export { SmartRouter } from './router.ts'added:deno_dist/router/smart-router/router.ts+65 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465/* eslint-disable @typescript-eslint/ban-ts-comment */import type { Router, Result } from '../../router.ts'import { UnsupportedPathError } from '../../router.ts'
export class SmartRouter<T> implements Router<T> { routers: Router<T>[] = [] routes?: [string, string, T][] = []
constructor(init: Pick<SmartRouter<T>, 'routers'>) { Object.assign(this, init) }
add(method: string, path: string, handler: T) { if (!this.routes) { throw new Error('Can not add a route since the matcher is already built.') }
this.routes.push([method, path, handler]) }
match(method: string, path: string): Result<T> | null { if (!this.routes) { throw new Error('Fatal error') }
const { routers, routes } = this const len = routers.length let i = 0 let res for (; i < len; i++) { const router = routers[i] try { routes.forEach((args) => { router.add(...args) }) res = router.match(method, path) } catch (e) { if (e instanceof UnsupportedPathError) { continue } throw e }
this.match = router.match.bind(router) this.routers = [router] this.routes = undefined break }
if (i === len) { // not found throw new Error('Fatal error') }
return res || null }
get activeRouter() { if (this.routes || this.routers.length !== 1) { throw new Error('No active router has been determined yet.') }
return this.routers[0] }}added:deno_dist/router/static-router/index.ts+1 added
1export { StaticRouter } from './router.ts'added:deno_dist/router/static-router/router.ts+81 added
1+/* eslint-disable @typescript-eslint/ban-ts-comment */2+import type { Router, Result } from '../../router.ts'3+import { METHOD_NAME_ALL, METHODS, UnsupportedPathError } from '../../router.ts'4+5+export class StaticRouter<T> implements Router<T> {6+ middleware: Record<string, Result<T>>7+ routes: Record<string, Record<string, Result<T>>>8+9+ constructor() {10+ this.middleware = {}11+12+ this.routes = {} as StaticRouter<T>['routes']13+ ;[METHOD_NAME_ALL, ...METHODS].forEach((method) => {14+ this.routes[method.toUpperCase()] = {}15+ })16+ }17+18+ add(method: string, path: string, handler: T) {19+ const { middleware, routes } = this20+21+ if (path === '/*') {22+ path = '*'23+ }24+25+ if (path === '*') {26+ if (method === METHOD_NAME_ALL) {27+ middleware[METHOD_NAME_ALL] ||= { handlers: [], params: {} }28+ Object.keys(middleware).forEach((m) => {29+ middleware[m].handlers.push(handler)30+ })31+ Object.keys(routes).forEach((m) => {32+ Object.values(routes[m]).forEach((matchRes) => matchRes.handlers.push(handler))33+ })34+ } else {35+ middleware[method] ||= {36+ handlers: [...(middleware[METHOD_NAME_ALL]?.handlers || [])],37+ params: {},38+ }39+ middleware[method].handlers.push(handler)40+ if (routes[method]) {41+ Object.values(routes[method]).forEach((matchRes) => matchRes.handlers.push(handler))42+ }43+ }44+ return45+ }46+47+ if (/\*|\/:/.test(path)) {48+ throw new UnsupportedPathError(path)49+ }50+51+ routes[method][path] ||= {52+ handlers: [53+ ...(routes[METHOD_NAME_ALL][path]?.handlers ||54+ middleware[method]?.handlers ||55+ middleware[METHOD_NAME_ALL]?.handlers ||56+ []),57+ ],58+ params: {},59+ }60+ if (method === METHOD_NAME_ALL) {61+ Object.keys(routes).forEach((m) => {62+ routes[m][path]?.handlers?.push(handler)63+ })64+ } else {65+ routes[method][path].handlers.push(handler)66+ }67+ }68+69+ match(method: string, path: string): Result<T> | null {70+ const { routes, middleware } = this71+72+ this.match = (method, path) =>73+ routes[method][path] ||74+ routes[METHOD_NAME_ALL][path] ||75+ middleware[method] ||76+ middleware[METHOD_NAME_ALL] ||77+ null78+79+ return this.match(method, path)80+ }81+}modified:deno_dist/hono.ts+10 added-5 removed
1 unmodified line2 import type { Context } from './context.ts'3 import { HonoContext } from './context.ts'4 import { extendRequestPrototype } from './request.ts'5 import type { Router } from './router.ts'6+import { METHODS } from './router.ts'7 import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router.ts'8+import { RegExpRouter } from './router/reg-exp-router/index.ts'9+import { SmartRouter } from './router/smart-router/index.ts'10+import { StaticRouter } from './router/static-router/index.ts'7-import { TrieRouter } from './router/trie-router/index.ts' // Default Router11+import { TrieRouter } from './router/trie-router/index.ts'12 import { getPathFromURL, mergePath } from './utils/url.ts'13 14 export interface ContextVariableMap {}15 55 unmodified lines71 ): U72 (path: string, ...handlers: Handler<string, E>[]): U73 }74 71-const methods = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const72-type Methods = typeof methods[number] | typeof METHOD_NAME_ALL_LOWERCASE75+type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE76 77 function defineDynamicClass(): {78 new <E extends Partial<Environment> = Environment, T extends string = string, U = Hono>(): {79 [K in Methods]: HandlerInterface<T, E, U>11 unmodified lines91 export class Hono<92 E extends Partial<Environment> = Environment,93 P extends string = '/'94 > extends defineDynamicClass()<E, P, Hono<E, P>> {92- readonly router: Router<Handler<string, E>> = new TrieRouter()95+ readonly router: Router<Handler<string, E>> = new SmartRouter({96+ routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],97+ })98 readonly strict: boolean = true // strict routing - default is true99 private _tempPath: string = ''100 private path: string = '/'101 3 unmodified lines105 super()106 107 extendRequestPrototype()108 104- const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]109+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]110 allMethods.map((method) => {111 this[method] = <Path extends string = ''>(112 args1: Path | Handler<ParamKeys<Path>, E>,113 ...args: [Handler<ParamKeys<Path>, E>]150 unmodified linesmodified:deno_dist/router.ts+3 added
12345672 unmodified lines101112131415export const METHOD_NAME_ALL = 'ALL' as constexport const METHOD_NAME_ALL_LOWERCASE = 'all' as constexport const METHODS = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const
export interface Router<T> { add(method: string, path: string, handler: T): void match(method: string, path: string): Result<T> | null2 unmodified linesexport interface Result<T> { handlers: T[] params: Record<string, string>}
export class UnsupportedPathError extends Error {}modified:src/router/reg-exp-router/router.ts+9 added-1 removed
1 /* eslint-disable @typescript-eslint/ban-ts-comment */2 import type { Router, Result } from '../../router'3-import { METHOD_NAME_ALL } from '../../router'3+import { METHOD_NAME_ALL, UnsupportedPathError } from '../../router'4 import type { ParamMap } from './trie'5 import { Trie } from './trie'6 7 interface Hint {191 unmodified lines199 return true200 }201 202 export class RegExpRouter<T> implements Router<T> {203+ allowAmbiguous: boolean = true204 routeData?: {205 index: number206 routes: Route<T>[]207 methods: Set<string>208 } = { index: 0, routes: [], methods: new Set() }209 210+ constructor(init: Partial<Pick<RegExpRouter<T>, 'allowAmbiguous'>> = {}) {211+ Object.assign(this, init)212+ }213+214 add(method: string, path: string, handler: T) {215 if (!this.routeData) {216 throw new Error('Can not add a route since the matcher is already built.')217 }224 unmodified lines442 }443 444 routes[i].hint.maybeHandler = false445 } else if (compareResult === 2) {446+ if (!this.allowAmbiguous) {447+ throw new UnsupportedPathError(routes[i].path)448+ }449 // ambiguous450 hasAmbiguous = true451 452 if (!verifyDuplicateParam([routes[i], routes[j]])) {30 unmodified linesadded:src/router/smart-router/index.ts+1 added
1export { SmartRouter } from './router'added:src/router/smart-router/router.test.ts+144 added
1+import { RegExpRouter } from '../reg-exp-router'2+import { StaticRouter } from '../static-router'3+import { TrieRouter } from '../trie-router'4+import { SmartRouter } from './router'5+6+describe('StaticRouter', () => {7+ describe('Basic Usage', () => {8+ const router = new SmartRouter<string>({9+ routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],10+ })11+12+ router.add('GET', '/hello', 'get hello')13+ router.add('POST', '/hello', 'post hello')14+15+ it('get, post hello', async () => {16+ let res = router.match('GET', '/hello')17+ expect(res).not.toBeNull()18+ expect(res?.handlers).toEqual(['get hello'])19+20+ res = router.match('POST', '/hello')21+ expect(res).not.toBeNull()22+ expect(res?.handlers).toEqual(['post hello'])23+24+ res = router.match('PUT', '/hello')25+ expect(res).toBeNull()26+27+ res = router.match('GET', '/')28+ expect(res).toBeNull()29+30+ expect(router.activeRouter).toBeInstanceOf(StaticRouter)31+ })32+ })33+34+ describe('Multi match', () => {35+ describe('Blog', () => {36+ const router = new SmartRouter<string>({37+ routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],38+ })39+40+ router.add('ALL', '*', 'middleware a')41+ router.add('GET', '*', 'middleware b')42+ router.add('GET', '/entry', 'get entries')43+ it('GET /', async () => {44+ const res = router.match('GET', '/')45+ expect(res).not.toBeNull()46+ expect(res?.handlers).toEqual(['middleware a', 'middleware b'])47+ expect(router.activeRouter).toBeInstanceOf(StaticRouter)48+ })49+ it('GET /entry', async () => {50+ const res = router.match('GET', '/entry')51+ expect(res).not.toBeNull()52+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entries'])53+ })54+ it('DELETE /entry', async () => {55+ const res = router.match('DELETE', '/entry')56+ expect(res).not.toBeNull()57+ expect(res?.handlers).toEqual(['middleware a'])58+ })59+ })60+ })61+})62+63+describe('RegExpRouter', () => {64+ describe('Complex', () => {65+ let router: SmartRouter<string>66+ beforeEach(() => {67+ router = new SmartRouter<string>({68+ routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],69+ })70+ })71+ 72+ it('Named Param', async () => {73+ router.add('GET', '/entry/:id', 'get entry')74+ const res = router.match('GET', '/entry/123')75+ expect(res).not.toBeNull()76+ expect(res?.handlers).toEqual(['get entry'])77+ expect(res?.params['id']).toBe('123')78+ expect(router.activeRouter).toBeInstanceOf(RegExpRouter)79+ })80+ 81+ it('Wildcard', async () => {82+ router.add('GET', '/wild/*/card', 'get wildcard')83+ const res = router.match('GET', '/wild/xxx/card')84+ expect(res).not.toBeNull()85+ expect(res?.handlers).toEqual(['get wildcard'])86+ })87+ 88+ it('Default', async () => {89+ router.add('GET', '/api/abc', 'get api')90+ router.add('GET', '/api/*', 'fallback')91+ let res = router.match('GET', '/api/abc')92+ expect(res).not.toBeNull()93+ expect(res?.handlers).toEqual(['get api', 'fallback'])94+ res = router.match('GET', '/api/def')95+ expect(res).not.toBeNull()96+ expect(res?.handlers).toEqual(['fallback'])97+ })98+ 99+ it('Regexp', async () => {100+ router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')101+ let res = router.match('GET', '/post/20210101/hello')102+ expect(res).not.toBeNull()103+ expect(res?.handlers).toEqual(['get post'])104+ expect(res?.params['date']).toBe('20210101')105+ expect(res?.params['title']).toBe('hello')106+ res = router.match('GET', '/post/onetwothree')107+ expect(res).toBeNull()108+ res = router.match('GET', '/post/123/123')109+ expect(res).toBeNull()110+ })111+ 112+ it('/*', async () => {113+ router.add('GET', '/api/*', 'auth middleware')114+ router.add('GET', '/api', 'top')115+ router.add('GET', '/api/posts', 'posts')116+ router.add('GET', '/api/*', 'fallback')117+ 118+ let res = router.match('GET', '/api')119+ expect(res).not.toBeNull()120+ expect(res?.handlers).toEqual(['auth middleware', 'top', 'fallback'])121+ 122+ res = router.match('GET', '/api/posts')123+ expect(res).not.toBeNull()124+ expect(res?.handlers).toEqual(['auth middleware', 'posts', 'fallback'])125+ })126+ })127+})128+129+describe('TrieRouter', () => {130+ const router = new SmartRouter<string>({131+ routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],132+ })133+134+ router.add('GET', '/:user/entries', 'get user entries')135+ router.add('GET', '/entry/:name', 'get entry')136+ it('GET /entry/entry', async () => {137+ const res = router.match('GET', '/entry/entries')138+ expect(res).not.toBeNull()139+ expect(res?.handlers).toEqual(['get user entries', 'get entry'])140+ expect(res?.params['user']).toBe('entry')141+ expect(res?.params['name']).toBe('entries')142+ expect(router.activeRouter).toBeInstanceOf(TrieRouter)143+ })144+})added:src/router/smart-router/router.ts+65 added
1+/* eslint-disable @typescript-eslint/ban-ts-comment */2+import type { Router, Result } from '../../router'3+import { UnsupportedPathError } from '../../router'4+5+export class SmartRouter<T> implements Router<T> {6+ routers: Router<T>[] = []7+ routes?: [string, string, T][] = []8+9+ constructor(init: Pick<SmartRouter<T>, 'routers'>) {10+ Object.assign(this, init)11+ }12+13+ add(method: string, path: string, handler: T) {14+ if (!this.routes) {15+ throw new Error('Can not add a route since the matcher is already built.')16+ }17+18+ this.routes.push([method, path, handler])19+ }20+21+ match(method: string, path: string): Result<T> | null {22+ if (!this.routes) {23+ throw new Error('Fatal error')24+ }25+26+ const { routers, routes } = this27+ const len = routers.length28+ let i = 029+ let res30+ for (; i < len; i++) {31+ const router = routers[i]32+ try {33+ routes.forEach((args) => {34+ router.add(...args)35+ })36+ res = router.match(method, path)37+ } catch (e) {38+ if (e instanceof UnsupportedPathError) {39+ continue40+ }41+ throw e42+ }43+44+ this.match = router.match.bind(router)45+ this.routers = [router]46+ this.routes = undefined47+ break48+ }49+50+ if (i === len) {51+ // not found52+ throw new Error('Fatal error')53+ }54+55+ return res || null56+ }57+58+ get activeRouter() {59+ if (this.routes || this.routers.length !== 1) {60+ throw new Error('No active router has been determined yet.')61+ }62+63+ return this.routers[0]64+ }65+}added:src/router/static-router/index.ts+1 added
1+export { StaticRouter } from './router'added:src/router/static-router/router.test.ts+49 added
1+import { StaticRouter } from './router'2+3+describe('Basic Usage', () => {4+ const router = new StaticRouter<string>()5+6+ router.add('GET', '/hello', 'get hello')7+ router.add('POST', '/hello', 'post hello')8+9+ it('get, post hello', async () => {10+ let res = router.match('GET', '/hello')11+ expect(res).not.toBeNull()12+ expect(res?.handlers).toEqual(['get hello'])13+14+ res = router.match('POST', '/hello')15+ expect(res).not.toBeNull()16+ expect(res?.handlers).toEqual(['post hello'])17+18+ res = router.match('PUT', '/hello')19+ expect(res).toBeNull()20+21+ res = router.match('GET', '/')22+ expect(res).toBeNull()23+ })24+})25+26+describe('Multi match', () => {27+ describe('Blog', () => {28+ const router = new StaticRouter<string>()29+30+ router.add('ALL', '*', 'middleware a')31+ router.add('GET', '*', 'middleware b')32+ router.add('GET', '/entry', 'get entries')33+ it('GET /', async () => {34+ const res = router.match('GET', '/')35+ expect(res).not.toBeNull()36+ expect(res?.handlers).toEqual(['middleware a', 'middleware b'])37+ })38+ it('GET /entry', async () => {39+ const res = router.match('GET', '/entry')40+ expect(res).not.toBeNull()41+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entries'])42+ })43+ it('DELETE /entry', async () => {44+ const res = router.match('DELETE', '/entry')45+ expect(res).not.toBeNull()46+ expect(res?.handlers).toEqual(['middleware a'])47+ })48+ })49+})added:src/router/static-router/router.ts+81 added
1+/* eslint-disable @typescript-eslint/ban-ts-comment */2+import type { Router, Result } from '../../router'3+import { METHOD_NAME_ALL, METHODS, UnsupportedPathError } from '../../router'4+5+export class StaticRouter<T> implements Router<T> {6+ middleware: Record<string, Result<T>>7+ routes: Record<string, Record<string, Result<T>>>8+9+ constructor() {10+ this.middleware = {}11+12+ this.routes = {} as StaticRouter<T>['routes']13+ ;[METHOD_NAME_ALL, ...METHODS].forEach((method) => {14+ this.routes[method.toUpperCase()] = {}15+ })16+ }17+18+ add(method: string, path: string, handler: T) {19+ const { middleware, routes } = this20+21+ if (path === '/*') {22+ path = '*'23+ }24+25+ if (path === '*') {26+ if (method === METHOD_NAME_ALL) {27+ middleware[METHOD_NAME_ALL] ||= { handlers: [], params: {} }28+ Object.keys(middleware).forEach((m) => {29+ middleware[m].handlers.push(handler)30+ })31+ Object.keys(routes).forEach((m) => {32+ Object.values(routes[m]).forEach((matchRes) => matchRes.handlers.push(handler))33+ })34+ } else {35+ middleware[method] ||= {36+ handlers: [...(middleware[METHOD_NAME_ALL]?.handlers || [])],37+ params: {},38+ }39+ middleware[method].handlers.push(handler)40+ if (routes[method]) {41+ Object.values(routes[method]).forEach((matchRes) => matchRes.handlers.push(handler))42+ }43+ }44+ return45+ }46+47+ if (/\*|\/:/.test(path)) {48+ throw new UnsupportedPathError(path)49+ }50+51+ routes[method][path] ||= {52+ handlers: [53+ ...(routes[METHOD_NAME_ALL][path]?.handlers ||54+ middleware[method]?.handlers ||55+ middleware[METHOD_NAME_ALL]?.handlers ||56+ []),57+ ],58+ params: {},59+ }60+ if (method === METHOD_NAME_ALL) {61+ Object.keys(routes).forEach((m) => {62+ routes[m][path]?.handlers?.push(handler)63+ })64+ } else {65+ routes[method][path].handlers.push(handler)66+ }67+ }68+69+ match(method: string, path: string): Result<T> | null {70+ const { routes, middleware } = this71+72+ this.match = (method, path) =>73+ routes[method][path] ||74+ routes[METHOD_NAME_ALL][path] ||75+ middleware[method] ||76+ middleware[METHOD_NAME_ALL] ||77+ null78+79+ return this.match(method, path)80+ }81+}modified:src/hono.test.ts+30 added-23 removed
96 unmodified lines97 })98 })99 100 describe('Routing', () => {101- const app = new Hono()102-101 it('Return it self', async () => {102+ const app = new Hono()103+104 const app2 = app.get('/', () => new Response('get /'))105 expect(app2).not.toBeUndefined()106 app2.delete('/', () => new Response('delete /'))107 8 unmodified lines116 expect(await res.text()).toBe('delete /')117 })118 119 it('Nested route', async () => {120+ const app = new Hono()121+122 const book = app.route('/book')123 book.get('/', (c) => c.text('get /book'))124 book.get('/:id', (c) => {125 return c.text('get /book/' + c.req.param('id'))28 unmodified lines154 expect(await res.text()).toBe('post /user/register')155 })156 157 describe('Chained route', () => {158+ const app = new Hono()159+160 app161 .get('/chained/:abc', (c) => {162 const abc = c.req.param('abc')163 return c.text(`GET for ${abc}`)614 unmodified lines778 })779 })780 781 describe('Duplicate param name', () => {778- it('self', () => {782+ it('self', async () => {783 const app = new Hono()780- expect(() => {781- app.get('/:id/:id', (c) => {782- const id = c.req.param('id')783- return c.text(`id is ${id}`)784- })785- }).toThrowError(/Duplicate param name/)784+ app.get('/:id/:id', (c) => {785+ const id = c.req.param('id')786+ return c.text(`id is ${id}`)787+ })788+ await expect(async () => {789+ await app.request('http://localhost/')790+ }).rejects.toThrowError(/Duplicate param name/)791 })792 788- it('parent', () => {793+ it('parent', async () => {794 const app = new Hono()795 app.get('/:id/:action', (c) => {796 return c.text('foo')797 })793- expect(() => {794- app.get('/posts/:id', (c) => {795- const id = c.req.param('id')796- return c.text(`id is ${id}`)797- })798- }).toThrowError(/Duplicate param name/)798+ app.get('/posts/:id', (c) => {799+ const id = c.req.param('id')800+ return c.text(`id is ${id}`)801+ })802+ await expect(async () => {803+ await app.request('http://localhost/')804+ }).rejects.toThrowError(/Duplicate param name/)805 })806 801- it('child', () => {807+ it('child', async () => {808 const app = new Hono()809 app.get('/posts/:id', (c) => {810 return c.text('foo')811 })806- expect(() => {807- app.get('/:id/:action', (c) => {808- const id = c.req.param('id')809- return c.text(`id is ${id}`)810- })811- }).toThrowError(/Duplicate param name/)812+ app.get('/:id/:action', (c) => {813+ const id = c.req.param('id')814+ return c.text(`id is ${id}`)815+ })816+ await expect(async () => {817+ await app.request('http://localhost/')818+ }).rejects.toThrowError(/Duplicate param name/)819 })820 821 it('hierarchy', () => {822 const app = new Hono()280 unmodified linesmodified:src/hono.ts+10 added-5 removed
1 unmodified line2 import type { Context } from './context'3 import { HonoContext } from './context'4 import { extendRequestPrototype } from './request'5 import type { Router } from './router'6+import { METHODS } from './router'7 import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router'8+import { RegExpRouter } from './router/reg-exp-router'9+import { SmartRouter } from './router/smart-router'10+import { StaticRouter } from './router/static-router'7-import { TrieRouter } from './router/trie-router' // Default Router11+import { TrieRouter } from './router/trie-router'12 import { getPathFromURL, mergePath } from './utils/url'13 14 export interface ContextVariableMap {}15 55 unmodified lines71 ): U72 (path: string, ...handlers: Handler<string, E>[]): U73 }74 71-const methods = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const72-type Methods = typeof methods[number] | typeof METHOD_NAME_ALL_LOWERCASE75+type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE76 77 function defineDynamicClass(): {78 new <E extends Partial<Environment> = Environment, T extends string = string, U = Hono>(): {79 [K in Methods]: HandlerInterface<T, E, U>11 unmodified lines91 export class Hono<92 E extends Partial<Environment> = Environment,93 P extends string = '/'94 > extends defineDynamicClass()<E, P, Hono<E, P>> {92- readonly router: Router<Handler<string, E>> = new TrieRouter()95+ readonly router: Router<Handler<string, E>> = new SmartRouter({96+ routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],97+ })98 readonly strict: boolean = true // strict routing - default is true99 private _tempPath: string = ''100 private path: string = '/'101 3 unmodified lines105 super()106 107 extendRequestPrototype()108 104- const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]109+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]110 allMethods.map((method) => {111 this[method] = <Path extends string = ''>(112 args1: Path | Handler<ParamKeys<Path>, E>,113 ...args: [Handler<ParamKeys<Path>, E>]150 unmodified linesmodified:src/router.ts+3 added
1 export const METHOD_NAME_ALL = 'ALL' as const2 export const METHOD_NAME_ALL_LOWERCASE = 'all' as const3+export const METHODS = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const4 5 export interface Router<T> {6 add(method: string, path: string, handler: T): void7 match(method: string, path: string): Result<T> | null2 unmodified lines10 export interface Result<T> {11 handlers: T[]12 params: Record<string, string>13 }14+15+export class UnsupportedPathError extends Error {}