pref: Optimize RegExpRouter (#135)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Use Record instead of `[key: string]: Type`. * Optimize RegExpRouter.
authored by Taku Amano · committed by GitHub · parent 515b7ff · Browse files · 3 files·+104 added−63 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+104 added−63 removed
- tests:+27 added−0 removed
- other:+77 added−63 removed
Provenance
- Commit
9921a3e- Tree
e5b2f2d- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
515b7ff
3 files changed+104 added−63 removed
modified:src/router/reg-exp-router/node.ts+1 added-3 removed
40 unmodified lines41424344454647454647484957 unmodified lines40 unmodified lines
export class Node { index?: number varIndex?: number children: { [key: string]: Node } = {} children: Record<string, Node> = {}
insert(tokens: readonly string[], index: number, paramMap: ParamMap, context: Context): void { if (tokens.length === 0) { this.index = index57 unmodified linesmodified:src/router/reg-exp-router/router.test.ts+27 added
12345661 unmodified lines686970717273747576777879808182838485868788899091929394959697import { RegExpRouter } from './router'import { METHOD_NAME_OF_ALL } from '../../router'
describe('Basic Usage', () => { const router = new RegExpRouter<string>()
61 unmodified lines res = router.match('GET', '/post/123/123') expect(res).toBeNull() })})
describe('Optimization for METHOD_NAME_OF_ALL', () => { let router: RegExpRouter<string> beforeEach(() => { router = new RegExpRouter<string>() })
it('Apply to all requests', async () => { router.add(METHOD_NAME_OF_ALL, '*', 'OK') const res = router.match('GET', '/entry/123') expect(res).not.toBeNull() expect(res.handler).toBe('OK') expect(res.params).toMatchObject({}) })
it('Apply to all requests under a specific path', async () => { router.add(METHOD_NAME_OF_ALL, '/path/to/*', 'OK') let res = router.match('GET', '/entry/123') expect(res).toBeNull()
res = router.match('GET', '/path/to/entry/123') expect(res).not.toBeNull() expect(res.handler).toBe('OK') expect(res.params).toMatchObject({}) })})modified:src/router/reg-exp-router/router.ts+76 added-60 removed
1 import { Router, Result, METHOD_NAME_OF_ALL } from '../../router'2-import type { ParamMap, ReplacementMap } from './trie'2+import type { ParamMap } from './trie'3 import { Trie } from './trie'4 5 type Route<T> = [string, T]6-type HandlerData<T> = [T, ParamMap]7-type Matcher<T> = [RegExp | true, ReplacementMap, HandlerData<T>[]]6+type HandlerData<T> = [T, ParamMap | null]7+type Matcher<T> = [RegExp, HandlerData<T>[]]8 9+const regExpMatchAll = new RegExp('')10+const emptyParam = {}11+12 export class RegExpRouter<T> extends Router<T> {10- routes?: {11- [method: string]: Route<T>[]12- } = {}13+ routes?: Record<string, Route<T>[]> = {}14 14- matchers?: {15- [method: string]: Matcher<T> | null16- } = null17-15 add(method: string, path: string, handler: T) {16 if (!this.routes) {17 throw new Error('Can not add a route since the matcher is already built.')18 }2 unmodified lines21 this.routes[method].push([path, handler])22 }23 24 match(method: string, path: string): Result<T> | null {28- if (!this.matchers) {29- this.buildAllMatchers()25+ const matchers = this.buildAllMatchers()30- }26 32- const matcher = this.matchers[method] || this.matchers[METHOD_NAME_OF_ALL]33- if (!matcher) {34- return null35- }27+ let match: typeof this.match28 37- const [regexp, replacementMap, handlers] = matcher38- if (regexp === true) {39- // '*'40- return new Result(handlers[0][0], {})29+ // Optimization for middleware30+ const methods = Object.keys(matchers)31+ if (methods.length === 1 && methods[0] === METHOD_NAME_OF_ALL) {32+ const [regexp, handlers] = matchers[METHOD_NAME_OF_ALL]33+ if (handlers.length === 1) {34+ const result = new Result(handlers[0][0], emptyParam)35+ if (regexp === regExpMatchAll) {36+ match = () => result37+ } else if (handlers.length === 1 && !handlers[0][1]) {38+ match = (_, path) => (regexp.test(path) ? result : null)39+ }40+ }41 }42 43- const match = path.match(regexp)44- if (!match) {45- return null46- }47- if (!replacementMap) {48- // there is only one route and no capture49- return new Result(handlers[0][0], {})50- }43+ match ||= (method, path) => {44+ const matcher = matchers[method] || matchers[METHOD_NAME_OF_ALL]45+ if (!matcher) {46+ return null47+ }48 52- const index = match.indexOf('', 1)53- const [handler, paramMap] = handlers[replacementMap[index]]54- const params: { [key: string]: string } = {}55- for (let i = 0; i < paramMap.length; i++) {56- params[paramMap[i][0]] = match[paramMap[i][1]]49+ const match = path.match(matcher[0])50+ if (!match) {51+ return null52+ }53+54+ const index = match.indexOf('', 1)55+ const [handler, paramMap] = matcher[1][index]56+ if (!paramMap) {57+ return new Result(handler, emptyParam)58+ }59+60+ const params: Record<string, string> = {}61+ for (let i = 0; i < paramMap.length; i++) {62+ params[paramMap[i][0]] = match[paramMap[i][1]]63+ }64+ return new Result(handler, params)65 }58- return new Result(handler, params)66+67+ this.match = match68+ return this.match(method, path)69 }70 61- private buildAllMatchers() {62- this.matchers ||= {}63-71+ private buildAllMatchers(): Record<string, Matcher<T>> {72+ const matchers: Record<string, Matcher<T>> = {}73 Object.keys(this.routes).forEach((method) => {65- this.buildMatcher(method)74+ matchers[method] = this.buildMatcher(method)75 })76 77 delete this.routes // to reduce memory usage78+79+ return matchers80 }81 71- private buildMatcher(method: string) {72- this.matchers ||= {}73-82+ private buildMatcher(method: string): Matcher<T> {83 const trie = new Trie()84 const handlers: HandlerData<T>[] = []85 86 const targetMethods = [method]2 unmodified lines89 }90 const routes = targetMethods.flatMap((method) => this.routes[method] || [])91 92 if (routes.length === 0) {84- this.matchers[method] = null85- return93+ return null94 }95 88- if (routes.length === 1 && routes[0][0] === '*') {89- this.matchers[method] = [true, null, [[routes[0][1], []]]]90- return91- }96+ if (method === METHOD_NAME_OF_ALL) {97+ if (routes.length === 1 && routes[0][0] === '*') {98+ return [regExpMatchAll, [[routes[0][1], null]]]99+ }100 93- if (routes.length === 1 && !routes[0][0].match(/:/)) {94- // there is only one route and no capture95- const tmp = routes[0][0].endsWith('*')96- ? routes[0][0].replace(/\/\*$/, '(?:$|/)') // /path/to/* => /path/to(?:$|/)97- : `${routes[0][0]}$` // /path/to/action => /path/to/action$98- const regExpStr = `^${tmp.replace(/\*/g, '[^/]+')}` // /prefix/*/path/to => /prefix/[^/]+/path/to99- this.matchers[method] = [new RegExp(regExpStr), null, [[routes[0][1], []]]]100- return101+ if (routes.length === 1 && !routes[0][0].match(/:/)) {102+ // there is only one route and no capture103+ const tmp = routes[0][0].endsWith('*')104+ ? routes[0][0].replace(/\/\*$/, '(?:$|/)') // /path/to/* => /path/to(?:$|/)105+ : `${routes[0][0]}$` // /path/to/action => /path/to/action$106+ const regExpStr = `^${tmp.replace(/\*/g, '[^/]+')}` // /prefix/*/path/to => /prefix/[^/]+/path/to107+ return [new RegExp(regExpStr), [[routes[0][1], null]]]108+ }109 }110 111 for (let i = 0; i < routes.length; i++) {112 const paramMap = trie.insert(routes[i][0], i)105- handlers[i] = [routes[i][1], paramMap]113+ handlers[i] = [routes[i][1], Object.keys(paramMap).length !== 0 ? paramMap : null]114 }115 116 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()117 for (let i = 0; i < handlers.length; i++) {118 const paramMap = handlers[i][1]119+ if (paramMap) {111- for (let i = 0; i < paramMap.length; i++) {112- paramMap[i][1] = paramReplacementMap[paramMap[i][1]]120+ for (let i = 0; i < paramMap.length; i++) {121+ paramMap[i][1] = paramReplacementMap[paramMap[i][1]]122+ }123 }124 }125 116- this.matchers[method] = [new RegExp(regexp), indexReplacementMap, handlers]126+ const handlerMap: HandlerData<T>[] = []127+ // using `in` because indexReplacementMap is a sparse array128+ for (const i in indexReplacementMap) {129+ handlerMap[i] = handlers[indexReplacementMap[i]]130+ }131+132+ return [regexp, handlerMap]133 }134 }