router.ts
This file
Path
src/router/pattern-router/router.ts
54 lines 路 1.6 KiB 路 TypeScript
Last changed by
fix(pattern-router/linear-router): prevent prefix overmatch on wildcard routes (#5252)Yusuke Wadabefore adoptiona194628
History of this fileTake it
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import type { Params, Result, Router } from '../../router'import { METHOD_NAME_ALL, UnsupportedPathError } from '../../router'
type Route<T> = [RegExp, string, T] // [pattern, method, handler]
const emptyParams = Object.create(null)
export class PatternRouter<T> implements Router<T> { name: string = 'PatternRouter' #routes: Route<T>[] = []
add(method: string, path: string, handler: T) { const suffix = path.endsWith('/*') ? '(?:$|/)' : path.endsWith('*') ? '' : '/?$' path = path.replace(/\*$/, '') if (path.at(-1) === '?') { path = path.slice(0, -1) this.add(method, path.replace(/\/[^/]+$/, ''), handler) }
const parts = (path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map( (part) => { const match = part.match(/^\/:([^{]+)(?:{(.*)})?/) return match ? `/(?<${match[1]}>${match[2] || '[^/]+'})` : part === '/*' ? '/[^/]+' : part.replace(/[.\\+*[^\]$()]/g, '\\$&') } )
try { this.#routes.push([new RegExp(`^${parts.join('')}${suffix}`), method, handler]) } catch { throw new UnsupportedPathError() } }
match(method: string, path: string): Result<T> { const handlers: [T, Params][] = []
for (let i = 0, len = this.#routes.length; i < len; i++) { const [pattern, routeMethod, handler] = this.#routes[i]
if (routeMethod === method || routeMethod === METHOD_NAME_ALL) { const match = pattern.exec(path) if (match) { handlers.push([handler, match.groups || emptyParams]) } } }
return [handlers] }}