All files / src/route/utility path-parser.ts

100% Statements 16/16
100% Branches 2/2
100% Functions 4/4
100% Lines 16/16

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47                  156x       156x 156x 156x   156x 214x 141x     73x   73x   73x     156x   156x 156x   156x             156x       10x  
interface ParsedPath {
	readonly regex: RegExp;
	readonly parameter_keys: string[];
}
 
class PathParser {
	private path: string;
 
	public constructor(path: string) {
		this.path = path;
	}
 
	public parse(): ParsedPath {
		const path = this.getPathWithoutLeadingSlash();
		const path_parts = path.split('/');
		const parameter_keys: string[] = [];
 
		const regex_parts = path_parts.map((path_part) => {
			if (!path_part.startsWith(':')) {
				return path_part;
			}
 
			const parameter_key = path_part.slice(1);
 
			parameter_keys.push(parameter_key);
 
			return '([^\\/]+)';
		});
 
		const querystring = '(\\?[^/]+)?';
 
		const regex_string = '^/' + regex_parts.join('/') + querystring + '$';
		const regex = new RegExp(regex_string);
 
		return {
			regex,
			parameter_keys
		};
	}
 
	private getPathWithoutLeadingSlash(): string {
		return this.path.slice(1);
	}
}
 
export default PathParser;