All files / src routes.map.ts

100% Statements 39/39
100% Branches 8/8
100% Functions 9/9
100% Lines 36/36

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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71    6x   32x 32x 10x   32x       19x       32x 31x 31x       6x       10x       2x       7x 7x 7x 13x   7x       8x 8x 8x 13x 13x 13x 33x 33x 33x   33x 33x 33x 60x 59x   60x   33x   13x   8x     6x    
'use strict';
 
export default class RoutesMap {
	public static add(method: string, route: string): void {
		method = method.toUpperCase();
		if (!RoutesMap._routes.has(method)) {
			RoutesMap._routes.set(method, new Set<string>());
		}
		RoutesMap._routes.get(method)!.add(route);
	}
 
	public static getMethods(): string[] {
		return Array.from(RoutesMap._routes.keys()).filter(Boolean).sort();
	}
 
	public static getRoutes(method: string): string[] | undefined {
		if (!method) return undefined;
		const routes = RoutesMap._routes.get(method.toUpperCase());
		return routes ? Array.from(routes).sort() : undefined;
	}
 
	public static keys(): string[] {
		return Array.from(RoutesMap._routes.keys());
	}
 
	public static values(): string[][] {
		return Array.from(RoutesMap._routes.values()).map((routeSet) => Array.from(routeSet));
	}
 
	public static clear(): void {
		RoutesMap._routes.clear();
	}
 
	public static list(): any {
		const obj: any = {};
		const methods: string[] = RoutesMap.getMethods();
		for (const method of methods) {
			obj[method] = RoutesMap.getRoutes(method);
		}
		return obj;
	}
 
	public static json(): any {
		const obj: any = {};
		const methods: string[] = RoutesMap.getMethods();
		for (const method of methods) {
			const apis: any = {};
			const routes: string[] = RoutesMap.getRoutes(method)!;
			for (const route of routes) {
				let parts: string[] = route.split('/');
				parts = parts.filter(Boolean);
				const last: string = parts.join('.');
				// Replace lodash _.set with native object assignment
				const keys = last.split('.');
				let current = apis;
				for (let i = 0; i < keys.length - 1; i++) {
					if (!(keys[i] in current)) {
						current[keys[i]] = {};
					}
					current = current[keys[i]];
				}
				current[keys[keys.length - 1]] = true;
			}
			obj[method] = apis;
		}
		return obj;
	}
 
	private static readonly _routes: Map<string, Set<string>> = new Map<string, Set<string>>();
}