RegExpRouter : Routing with order specification. (#267)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Taku Amano · committed by GitHub · parent 4a906a8 · Browse files · 2 files·+91 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+91 added−27 removed
- tests:+18 added−3 removed
- other:+73 added−24 removed
Provenance
- Commit
a18edd5- Tree
7335671- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
4a906a8
2 files changed+91 added−27 removed
modified:src/router/reg-exp-router/router.test.ts+18 added-3 removed
48 unmodified lines49 router.add('GET', '/api/abc', 'get api')50 router.add('GET', '/api/*', 'fallback')51 let res = router.match('GET', '/api/abc')52 expect(res).not.toBeNull()53- expect(res.handlers).toEqual(['fallback', 'get api'])53+ expect(res.handlers).toEqual(['get api', 'fallback'])54 res = router.match('GET', '/api/def')55 expect(res).not.toBeNull()56 expect(res.handlers).toEqual(['fallback'])57 })9 unmodified lines67 expect(res).toBeNull()68 res = router.match('GET', '/post/123/123')69 expect(res).toBeNull()70 })71+72+ it('/*', async () => {73+ router.add('GET', '/api/*', 'auth middleware')74+ router.add('GET', '/api', 'top')75+ router.add('GET', '/api/posts', 'posts')76+ router.add('GET', '/api/*', 'fallback')77+78+ let res = router.match('GET', '/api')79+ expect(res).not.toBeNull()80+ expect(res.handlers).toEqual(['auth middleware', 'top', 'fallback'])81+82+ res = router.match('GET', '/api/posts')83+ expect(res).not.toBeNull()84+ expect(res.handlers).toEqual(['auth middleware', 'posts', 'fallback'])85+ })86 })87 73-describe('Order independent', () => {88+describe('Registration order', () => {89 let router: RegExpRouter<string>90 beforeEach(() => {91 router = new RegExpRouter<string>()92 })10 unmodified lines103 router.add('GET', '/posts/:id', 'bar')104 router.add('GET', '/:type/:action', 'foo')105 const res = router.match('GET', '/posts/123')106 expect(res).not.toBeNull()92- expect(res.handlers).toEqual(['foo', 'bar'])107+ expect(res.handlers).toEqual(['bar', 'foo'])108 })109 })110 111 describe('Optimization for METHOD_NAME_OF_ALL', () => {145 unmodified linesmodified:src/router/reg-exp-router/router.ts+73 added-24 removed
9 unmodified lines10 paramIndexList: number[]11 maybeHandler: boolean12 namedParams: [number, string, string][]13 }14+interface HandlerWithSortIndex<T> {15+ handler: T16+ index: number17+ componentsLength: number18+}19 interface Route<T> {20 method: string21 path: string22 hint: Hint18- handlers: T[]19- middleware: T[]23+ handlers: HandlerWithSortIndex<T>[]24+ middleware: HandlerWithSortIndex<T>[]25 paramAliasMap: Record<string, string[]>26 }27 type HandlerData<T> = [T[], ParamMap | null]28 type Matcher<T> = [RegExp, HandlerData<T>[]]29+type HandlerDataWithSortIndex<T> = [HandlerWithSortIndex<T>[], ParamMap | null]30+type MatcherWithSortIndex<T> = [RegExp, HandlerDataWithSortIndex<T>[]]31+type AnyMatcher<T> = Matcher<T> | MatcherWithSortIndex<T>32 33 type CompareResult =34 | 0 // different35 | 1 // included70 unmodified lines106 107 return i === b.hint.regExpComponents.length || a.hint.endWithWildcard ? 1 : 0108 }109 110+function compareHandler(a: HandlerWithSortIndex<any>, b: HandlerWithSortIndex<any>) {111+ return a.componentsLength !== b.componentsLength112+ ? a.componentsLength - b.componentsLength113+ : a.index - b.index114+}115+116+function getSortedHandlers<T>(117+ handlers: HandlerWithSortIndex<T>[] | IterableIterator<HandlerWithSortIndex<T>>118+): T[] {119+ return [...handlers].sort(compareHandler).map((h) => h.handler)120+}121+122 function buildMatcherFromPreprocessedRoutes<T>(123 routes: Route<T>[],124 hasAmbiguous: boolean = false105-): Matcher<T> {125+): AnyMatcher<T> {126 const trie = new Trie({ reverse: hasAmbiguous })107- const handlers: HandlerData<T>[] = []127+ const handlers: HandlerData<T>[] | HandlerDataWithSortIndex<T>[] = []128 129 if (routes.length === 0) {130 return nullMatcher131 }3 unmodified lines135 handlers[i] = [136 [...routes[i].middleware, ...routes[i].handlers],137 Object.keys(paramMap).length !== 0 ? paramMap : null,138 ]139+ if (!hasAmbiguous) {140+ handlers[i][0] = getSortedHandlers(handlers[i][0] as HandlerWithSortIndex<T>[])141+ }142 }143 144 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()145 for (let i = 0, len = handlers.length; i < len; i++) {11 unmodified lines157 }158 }159 }160 138- const handlerMap: HandlerData<T>[] = []161+ const handlerMap: HandlerData<T>[] | HandlerDataWithSortIndex<T>[] = []162 // using `in` because indexReplacementMap is a sparse array163 for (const i in indexReplacementMap) {164 handlerMap[i] = handlers[indexReplacementMap[i]]165 }166 144- return [regexp, handlerMap]167+ return [regexp, handlerMap] as AnyMatcher<T>168 }169 170 function verifyDuplicateParam<T>(routes: Route<T>[]): boolean {171 const nameMap: Record<string, number> = {}29 unmodified lines201 }202 203 export class RegExpRouter<T> extends Router<T> {204 routeData?: {205+ index: number206 routes: Route<T>[]207 methods: Set<string>184- } = { routes: [], methods: new Set() }208+ } = { index: 0, routes: [], methods: new Set() }209 210 add(method: string, path: string, handler: T) {211 if (!this.routeData) {212 throw new Error('Can not add a route since the matcher is already built.')213 }214+ this.routeData.index++190- const { routes, methods } = this.routeData215+ const { index, routes, methods } = this.routeData216 217 if (path === '/*') {218 path = '*'219 }220 221+ const hint = initHint(path)222+ const handlerWithSortIndex = {223+ index,224+ handler,225+ componentsLength: hint.components.length,226+ }227+228 for (let i = 0, len = routes.length; i < len; i++) {229 if (routes[i].method === method && routes[i].path === path) {198- routes[i].handlers.push(handler)230+ routes[i].handlers.push(handlerWithSortIndex)231 return232 }233 }234 235 methods.add(method)236 routes.push({237 method,238 path,207- handlers: [handler],208- hint: initHint(path),239+ hint,240+ handlers: [handlerWithSortIndex],241 middleware: [],242 paramAliasMap: {},243 })244 }2 unmodified lines247 const [primaryMatchers, secondaryMatchers, hasAmbiguous] = this.buildAllMatchers()248 249 this.match = hasAmbiguous250 ? (method, path) => {219- const matcher = primaryMatchers[method] || primaryMatchers[METHOD_NAME_ALL]251+ const matcher = (primaryMatchers[method] ||252+ primaryMatchers[METHOD_NAME_ALL]) as MatcherWithSortIndex<T>253 let match = path.match(matcher[0])254 255 if (!match) {256 // do not support secondary matchers here.257 return null258 }259 260 const params: Record<string, string> = {}228- const handlers: Set<T> = new Set()261+ const handlers: Set<HandlerWithSortIndex<T>> = new Set()262 let regExpSrc = matcher[0].source263 while (match) {264 let index = match.indexOf('', 1)265 for (;;) {22 unmodified lines288 )289 match = path.match(new RegExp(regExpSrc))290 }291 259- return new Result([...handlers.values()], params)292+ return new Result(getSortedHandlers(handlers.values()), params)293 }294 : (method, path) => {262- let matcher = primaryMatchers[method] || primaryMatchers[METHOD_NAME_ALL]295+ let matcher = (primaryMatchers[method] || primaryMatchers[METHOD_NAME_ALL]) as Matcher<T>296 let match = path.match(matcher[0])297 298 if (!match) {299 const matchers = secondaryMatchers[method] || secondaryMatchers[METHOD_NAME_ALL]300 for (let i = 0, len = matchers.length; i < len && !match; i++) {268- matcher = matchers[i]301+ matcher = matchers[i] as Matcher<T>302 match = path.match(matcher[0])303 }304 305 if (!match) {1 unmodified line307 }308 }309 310 const index = match.indexOf('', 1)278- const [handler, paramMap] = matcher[1][index]311+ const [handlers, paramMap] = matcher[1][index]312 if (!paramMap) {280- return new Result(handler, emptyParam)313+ return new Result(handlers, emptyParam)314 }315 316 const params: Record<string, string> = {}317 for (let i = 0, len = paramMap.length; i < len; i++) {318 params[paramMap[i][0]] = match[paramMap[i][1]]319 }320 288- return new Result(handler, params)321+ return new Result(handlers, params)322 }323 324 return this.match(method, path)325 }326 294- private buildAllMatchers(): [Record<string, Matcher<T>>, Record<string, Matcher<T>[]>, boolean] {327+ private buildAllMatchers(): [328+ Record<string, AnyMatcher<T>>,329+ Record<string, AnyMatcher<T>[]>,330+ boolean331+ ] {332 this.routeData.routes.sort(({ hint: a }, { hint: b }) => {333 if (a.componentsLength !== b.componentsLength) {334 return a.componentsLength - b.componentsLength335 }17 unmodified lines353 }354 return 0355 })356 320- const primaryMatchers: Record<string, Matcher<T>> = {}321- const secondaryMatchers: Record<string, Matcher<T>[]> = {}357+ const primaryMatchers: Record<string, AnyMatcher<T>> = {}358+ const secondaryMatchers: Record<string, AnyMatcher<T>[]> = {}359 let hasAmbiguous = false360 this.routeData.methods.forEach((method) => {361 let _hasAmbiguous362 ;[primaryMatchers[method], secondaryMatchers[method], _hasAmbiguous] =7 unmodified lines370 371 return [primaryMatchers, secondaryMatchers, hasAmbiguous]372 }373 337- private buildMatcher(method: string): [Matcher<T>, Matcher<T>[], boolean] {374+ private buildMatcher(method: string): [AnyMatcher<T>, AnyMatcher<T>[], boolean] {375 let hasAmbiguous = false376 const targetMethods = new Set([method, METHOD_NAME_ALL])377 const routes = this.routeData.routes.filter(({ method }) => targetMethods.has(method))378 30 unmodified lines409 routes[j].path = components.join('')410 }411 }412 413+ if (routes[j].hint.components.length < routes[i].hint.components.length) {414+ const componentsLength = routes[j].hint.components.length415+ routes[j].middleware.push(416+ ...routes[i].handlers.map((h) => ({417+ componentsLength,418+ index: h.index,419+ handler: h.handler,420+ }))421+ )422+ } else {376- routes[j].middleware.push(...routes[i].handlers)423+ routes[j].middleware.push(...routes[i].handlers)424+ }425+426 routes[i].hint.maybeHandler = false427 } else if (compareResult === 2) {428 // ambiguous429 hasAmbiguous = true32 unmodified lines