Skip to content
Myr

refactor: internal structure of `PreparedRegExpRouter` for optimization and added tests (#4456)

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

* refactor(reg-exp-router): it is difficult to use in JSON.stringify, so `undefined` is not used. * refactor(reg-exp-router): a safer and simpler way to embed regular expressions. * refactor(reg-exp-router): narrowed the scope of `all` variables. * refactor(reg-exp-router): use `for...in` instead of `Object.keys` * refactor(reg-exp-router): avoid creating temporary arrays `method === METHOD_NAME_ALL ? Object.keys(this.#matchers) : [method]` * refactor(reg-exp-router): skip adding wildcard routes to relocate map * test(reg-exp-router): add test cases for buildInitParams() and serializeInitParams()

authored by Taku Amano · committed by GitHub · parent 3b8642b · Browse files · 2 files+147 added−44 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+147 added−44 removed

  • tests:+84 added−0 removed
  • other:+63 added−44 removed

2 files+147 added−44 removed

modified:src/router/reg-exp-router/prepared-router.test.ts+84 added
modified:src/router/reg-exp-router/prepared-router.ts+63 added-44 removed
2 unmodified lines
3import type { HandlerData, Matcher, MatcherMap, StaticMap } from './matcher'4import { match, buildAllMatchersKey, emptyParam } from './matcher'5import { RegExpRouter } from './router'67type RelocateMap = Record<string, [(number | string)[], ParamIndexMap | undefined][]>7type RelocateMap = Record<string, ([(number | string)[], ParamIndexMap] | [(number | string)[]])[]>89export class PreparedRegExpRouter<T> implements Router<T> {10 name: string = 'PreparedRegExpRouter'11 #matchers: MatcherMap<T>
3 unmodified lines
15 this.#matchers = matchers16 this.#relocateMap = relocateMap17 }1819 #addWildcard(method: string, handlerData: [T, ParamIndexMap]) {20 const matcher = this.#matchers[method] as Matcher<T>21 matcher[1].forEach((list) => list && list.push(handlerData))22 Object.values(matcher[2]).forEach((list) => (list[0] as [T, ParamIndexMap][]).push(handlerData))23 }2425 #addPath(26 method: string,27 path: string,28 handler: T,29 indexes: (number | string)[],30 map: ParamIndexMap | undefined31 ) {32 const matcher = this.#matchers[method] as Matcher<T>33 if (!map) {34 // assumed to be a static route35 matcher[2][path][0].push([handler, {}])36 } else {37 indexes.forEach((index) => {38 if (typeof index === 'number') {39 matcher[1][index].push([handler, map])40 } else {41 ;(matcher[2][index || path][0] as [T, ParamIndexMap][]).push([handler, map])42 }43 })44 }45 }4647 add(method: string, path: string, handler: T) {20 const all = this.#matchers[METHOD_NAME_ALL] as Matcher<T>21 this.#matchers[method] ||= [22 all[0],23 all[1].map((list) => (Array.isArray(list) ? list.slice() : 0)) as HandlerData<T>[],24 Object.keys(all[2]).reduce((obj, key) => {25 obj[key] = [all[2][key][0].slice(), emptyParam] as Result<T>26 return obj27 }, {} as StaticMap<T>),28 ]48 if (!this.#matchers[method]) {49 const all = this.#matchers[METHOD_NAME_ALL] as Matcher<T>50 const staticMap = {} as StaticMap<T>51 for (const key in all[2]) {52 staticMap[key] = [all[2][key][0].slice(), emptyParam] as Result<T>53 }54 this.#matchers[method] = [55 all[0],56 all[1].map((list) => (Array.isArray(list) ? list.slice() : 0)) as HandlerData<T>[],57 staticMap,58 ]59 }6061 if (path === '/*' || path === '*') {31 const defaultHandlerData: [T, ParamIndexMap] = [handler, {}]32 ;(method === METHOD_NAME_ALL ? Object.keys(this.#matchers) : [method]).forEach((m) => {33 const matcher = this.#matchers[m] as Matcher<T>34 matcher[1].forEach((list) => list && list.push(defaultHandlerData))35 Object.values(matcher[2]).forEach((list) =>36 (list[0] as [T, ParamIndexMap][]).push(defaultHandlerData)37 )38 })62 const handlerData: [T, ParamIndexMap] = [handler, {}]63 if (method === METHOD_NAME_ALL) {64 for (const m in this.#matchers) {65 this.#addWildcard(m, handlerData)66 }67 } else {68 this.#addWildcard(method, handlerData)69 }70 return71 }7273 const data = this.#relocateMap[path]74 if (!data) {75 throw new Error(`Path ${path} is not registered`)76 }77 for (const [indexes, map] of data) {47 ;(method === METHOD_NAME_ALL ? Object.keys(this.#matchers) : [method]).forEach((m) => {48 const matcher = this.#matchers[m] as Matcher<T>49 if (!map) {50 // assumed to be a static route51 matcher[2][path][0].push([handler, {}])52 } else {53 indexes.forEach((index) => {54 if (typeof index === 'number') {55 matcher[1][index].push([handler, map])56 } else {57 ;(matcher[2][index || path][0] as [T, ParamIndexMap][]).push([handler, map])58 }59 })78 if (method === METHOD_NAME_ALL) {79 for (const m in this.#matchers) {80 this.#addPath(m, path, handler, indexes, map)81 }61 })82 } else {83 this.#addPath(method, path, handler, indexes, map)84 }85 }86 }8788 [buildAllMatchersKey](): MatcherMap<T> {
15 unmodified lines
104 const all = matchers[METHOD_NAME_ALL] as Matcher<string>105106 const relocateMap: RelocateMap = {}107 for (const path of paths) {108 if (path === '/*' || path === '*') {109 continue110 }111 all[1].forEach((list, i) => {112 list.forEach(([p, map]) => {113 if (p === path) {114 if (relocateMap[path]) {
12 unmodified lines
127 })128 for (const path2 in all[2]) {129 all[2][path2][0].forEach(([p]) => {130 if (p === path) {105 relocateMap[path] ||= [[[], undefined]]131 relocateMap[path] ||= [[[]]]132 const value = path2 === path ? '' : path2133 if (relocateMap[path][0][0].findIndex((v) => v === value) === -1) {134 relocateMap[path][0][0].push(value)135 }
14 unmodified lines
150151export const serializeInitParams: (152 params: ConstructorParameters<typeof PreparedRegExpRouter>153) => string = ([matchers, relocateMap]) => {128 for (const method in matchers) {129 const matcher = matchers[method] as Matcher<string>130 // escape the regular expression to serialize it with `JSON.stringify`131 ;(matcher[0] as RegExp & { toJSON: () => string }).toJSON = function () {132 return `@${this.toString()}@`133 }134 }135 // unescape the regular expression so that it can be deserialized with `eval`.136 const matchersStr = JSON.stringify(matchers).replace(/"@(.+?)@"/g, (_, str) =>137 str.replace(/\\\\/g, '\\')138 )154 // Embed the regular expression as a result of `toString()` so that it can be evaluated as JavaScript.155 const matchersStr = JSON.stringify(matchers, (_, value) =>156 value instanceof RegExp ? `##${value.toString()}##` : value157 ).replace(/"##(.+?)##"/g, (_, str) => str.replace(/\\\\/g, '\\'))158 const relocateMapStr = JSON.stringify(relocateMap)159 return `[${matchersStr},${relocateMapStr}]`160}