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()
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
Provenance
- Commit
ff715fc- Tree
f0af8c2- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
3b8642b
2 files changed+147 added−44 removed
modified:src/router/reg-exp-router/prepared-router.test.ts+84 added
1234562 unmodified lines6869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154import { METHOD_NAME_ALL } from '../../router'import { runTest } from '../common.case.test'import { buildInitParams, serializeInitParams, PreparedRegExpRouter } from './prepared-router'
describe('PreparedRegExpRouter', async () => {62 unmodified lines expect(() => router.add('GET', '/unknown', 'get hello')).toThrowError() }) })})
describe('buildInitParams() and serializeInitParams()', () => { it('should build empty init params', () => { const params = buildInitParams({ paths: [], }) expect(params).toEqual([{ [METHOD_NAME_ALL]: [/^$/, [], {}] }, {}]) expect((0, eval)(serializeInitParams(params))).toEqual(params) })
it('should build init params with one static path', () => { const params = buildInitParams({ paths: ['/hello'], }) expect(params).toEqual([ { [METHOD_NAME_ALL]: [ /^$/, [], { '/hello': [[], []], }, ], }, { '/hello': [[['']]], }, ]) expect((0, eval)(serializeInitParams(params))).toEqual(params) })
it('should build init params with paths with params', () => { const params = buildInitParams({ paths: ['/hello/:name', '/hello/:name/posts/:postId'], }) expect(params).toEqual([ { [METHOD_NAME_ALL]: [/^\/hello\/([^/]+)(?:$()|\/posts\/([^/]+)$())/, [0, 0, [], 0, []], {}], }, { '/hello/:name': [[[2], { name: 1 }]], '/hello/:name/posts/:postId': [[[4], { name: 1, postId: 3 }]], }, ]) expect((0, eval)(serializeInitParams(params))).toEqual(params) })
it('should build init params with wildcard', () => { const params = buildInitParams({ paths: ['*'], }) expect(params).toEqual([ { [METHOD_NAME_ALL]: [/^.*$()/, [0, []], {}], }, {}, ]) expect((0, eval)(serializeInitParams(params))).toEqual(params) })
it('should build init params with complex path', () => { const params = buildInitParams({ paths: ['/hello', '/hello/:name', '/hello/:name/posts/:postId', '*'], }) expect(params).toEqual([ { [METHOD_NAME_ALL]: [ /^(?:\/hello\/([^/]+)(?:$()|\/posts\/([^/]+)$())|.*$())/, [0, 0, [], 0, [], []], { '/hello': [[], []], }, ], }, { '/hello': [[['']]], '/hello/:name': [[[2], { name: 1 }]], '/hello/:name/posts/:postId': [[[4], { name: 1, postId: 3 }]], }, ]) expect((0, eval)(serializeInitParams(params))).toEqual(params) })})modified:src/router/reg-exp-router/prepared-router.ts+63 added-44 removed
2 unmodified lines3 import type { HandlerData, Matcher, MatcherMap, StaticMap } from './matcher'4 import { match, buildAllMatchersKey, emptyParam } from './matcher'5 import { RegExpRouter } from './router'6 7-type RelocateMap = Record<string, [(number | string)[], ParamIndexMap | undefined][]>7+type RelocateMap = Record<string, ([(number | string)[], ParamIndexMap] | [(number | string)[]])[]>8 9 export class PreparedRegExpRouter<T> implements Router<T> {10 name: string = 'PreparedRegExpRouter'11 #matchers: MatcherMap<T>3 unmodified lines15 this.#matchers = matchers16 this.#relocateMap = relocateMap17 }18 19+ #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+ }24+25+ #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+ }46+47 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+ }60 61 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 }72 73 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 }87 88 [buildAllMatchersKey](): MatcherMap<T> {15 unmodified lines104 const all = matchers[METHOD_NAME_ALL] as Matcher<string>105 106 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 lines127 })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 lines150 151 export 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 }