Add support for regex matching routes
This commit is contained in:
57
lib/src/http/routing/RegExRoute.ts
Normal file
57
lib/src/http/routing/RegExRoute.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import {Route, RouteParameters} from './Route.ts'
|
||||
import {Logging} from '../../service/logging/Logging.ts'
|
||||
import {make} from '../../../../di/src/global.ts'
|
||||
|
||||
export class RegExRoute extends Route {
|
||||
protected key_regex: RegExp
|
||||
|
||||
constructor(
|
||||
protected base: string,
|
||||
protected key: string,
|
||||
) {
|
||||
super(base)
|
||||
this.key_regex = this.build_regex(key)
|
||||
}
|
||||
|
||||
public get route() {
|
||||
return this.base + this.key
|
||||
}
|
||||
|
||||
public match(incoming: string): boolean {
|
||||
if ( !incoming.toLowerCase().startsWith(this.base) ) return false
|
||||
incoming = incoming.substr(this.base.length)
|
||||
|
||||
const success = this.key_regex.test(incoming)
|
||||
|
||||
if ( !success ) {
|
||||
make(Logging).debug(`RegExRoute match failed. (Testing: ${incoming}, Key: ${this.key}, Rex: ${this.key_regex})`)
|
||||
}
|
||||
|
||||
return success
|
||||
}
|
||||
|
||||
public build_parameters(incoming: string): RouteParameters {
|
||||
if ( incoming.toLowerCase().startsWith(this.base) ) incoming = incoming.substr(this.base.length)
|
||||
|
||||
const results = this.key_regex.exec(incoming.toLowerCase())
|
||||
if ( !results ) return {}
|
||||
|
||||
const [match, ...wildcards] = results
|
||||
const params: RouteParameters = {}
|
||||
let current_wildcard: number = 1
|
||||
|
||||
for ( const wild of wildcards ) {
|
||||
params[`$${current_wildcard}`] = wild
|
||||
current_wildcard += 1
|
||||
}
|
||||
|
||||
return params
|
||||
}
|
||||
|
||||
protected build_regex(key: string) {
|
||||
if ( !key.startsWith('rex ') ) {
|
||||
throw new TypeError(`Invalid regular expression route pattern: ${key}`)
|
||||
}
|
||||
return new RegExp(key.substr(4))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user