Skip to content
Myr

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

3 files+104 added−63 removed

modified:src/router/reg-exp-router/node.ts+1 added-3 removed
modified:src/router/reg-exp-router/router.test.ts+27 added
modified:src/router/reg-exp-router/router.ts+76 added-60 removed
1import { Router, Result, METHOD_NAME_OF_ALL } from '../../router'2import type { ParamMap, ReplacementMap } from './trie'2import type { ParamMap } from './trie'3import { Trie } from './trie'45type Route<T> = [string, T]6type HandlerData<T> = [T, ParamMap]7type Matcher<T> = [RegExp | true, ReplacementMap, HandlerData<T>[]]6type HandlerData<T> = [T, ParamMap | null]7type Matcher<T> = [RegExp, HandlerData<T>[]]89const regExpMatchAll = new RegExp('')10const emptyParam = {}1112export class RegExpRouter<T> extends Router<T> {10 routes?: {11 [method: string]: Route<T>[]12 } = {}13 routes?: Record<string, Route<T>[]> = {}1414 matchers?: {15 [method: string]: Matcher<T> | null16 } = null1715 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 lines
21 this.routes[method].push([path, handler])22 }2324 match(method: string, path: string): Result<T> | null {28 if (!this.matchers) {29 this.buildAllMatchers()25 const matchers = this.buildAllMatchers()30 }2632 const matcher = this.matchers[method] || this.matchers[METHOD_NAME_OF_ALL]33 if (!matcher) {34 return null35 }27 let match: typeof this.match2837 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 }4243 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 }4852 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 }5354 const index = match.indexOf('', 1)55 const [handler, paramMap] = matcher[1][index]56 if (!paramMap) {57 return new Result(handler, emptyParam)58 }5960 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)6667 this.match = match68 return this.match(method, path)69 }7061 private buildAllMatchers() {62 this.matchers ||= {}6371 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 })7677 delete this.routes // to reduce memory usage7879 return matchers80 }8171 private buildMatcher(method: string) {72 this.matchers ||= {}7382 private buildMatcher(method: string): Matcher<T> {83 const trie = new Trie()84 const handlers: HandlerData<T>[] = []8586 const targetMethods = [method]
2 unmodified lines
89 }90 const routes = targetMethods.flatMap((method) => this.routes[method] || [])9192 if (routes.length === 0) {84 this.matchers[method] = null85 return93 return null94 }9588 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 }10093 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 }110111 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 }115116 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 }125116 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 }131132 return [regexp, handlerMap]133 }134}