All files / src routes.map.ts

100% Statements 30/30
100% Branches 2/2
100% Functions 8/8
100% Lines 30/30

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    1x     1x   5x 5x 5x 5x 5x       17x       29x       6x       6x       1x       7x 7x 7x 13x   7x       6x 6x 6x 10x 10x 10x 29x 29x 29x 29x   10x   6x     1x    
'use strict';
 
import * as _ from 'lodash';
 
// TODO: convert to a fastify plugin! See: https://github.com/fastify/fastify-routes
export default class RoutesMap {
	public static add(method: string, route: string): void {
		method = _.toUpper(method);
		let routes: string[] = RoutesMap._routes.get(method) || [];
		routes.push(route);
		routes = _.sortBy(_.compact(_.uniq(routes)));
		RoutesMap._routes.set(method, routes);
	}
 
	public static getMethods(): string[] {
		return _.sortBy(_.compact(Array.from(RoutesMap._routes.keys())));
	}
 
	public static getRoutes(method: string): string[] | null {
		return RoutesMap._routes.get(_.toUpper(method));
	}
 
	public static keys(): string[] {
		return Array.from(RoutesMap._routes.keys());
	}
 
	public static values(): string[][] {
		return Array.from(RoutesMap._routes.values());
	}
 
	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[] = _.split(route, '/');
				parts = _.compact(parts);
				const last: string = _.join(parts, '.');
				_.set(apis, last, true);
			}
			obj[method] = apis;
		}
		return obj;
	}
 
	private static readonly _routes: Map<string, string[]> = new Map<string, string[]>();
}