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.

79 lines
2.1 KiB

import {Route, RouteParameters} from './Route.ts'
import {Logging} from '../../service/logging/Logging.ts'
import {make} from '../../../../di/src/global.ts'
/**
* Route that is defined and matched by regex
* @extends Route
*/
export class RegExRoute extends Route {
/**
* Generated regex for the definition.
* @type RegExp
*/
protected key_regex: RegExp
constructor(
/**
* Route base string.
* @type string
*/
protected base: string,
/**
* Regex key.
* @type 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
}
/**
* Build the regex for the given route, from its parsed key.
* @param {string} key
* @return RegExp
*/
protected build_regex(key: string) {
if ( !key.startsWith('rex ') ) {
throw new TypeError(`Invalid regular expression route pattern: ${key}`)
}
return new RegExp(key.substr(4))
}
}