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.

60 lines
1.6 KiB

import {Route, RouteParameters} from './Route.ts'
/**
* A route that contains deep wild-cards.
* @extends Route
*/
export class DeepmatchRoute extends Route {
/**
* The built regex for parsing the route.
* @type RegExp
*/
protected base_regex: RegExp
constructor(
/**
* Base route definition.
* @type string
*/
protected base: string
) {
super(base)
this.base_regex = this.build_regex(this.split(base))
}
public match(incoming: string): boolean {
return this.base_regex.test(incoming.toLowerCase())
}
public build_parameters(incoming: string): RouteParameters {
const results = this.base_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 object for the given route parts.
* @param {Array<string>} base_parts
*/
protected build_regex(base_parts: string[]) {
const deepmatch_group = '([a-zA-Z0-9\\-\\_\\.\\/]+)' // allows for alphanum, -, _, ., and /
const shallowmatch_group = '([a-zA-Z0-9\\-\\.\\_]+)' // allows for alphanum, -, ., and _
const regex = base_parts.map(part => {
return part.split('**').join(deepmatch_group).split('*').join(shallowmatch_group)
}).join('\\/')
return new RegExp(regex)
}
}