You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.6 KiB

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))
}
}