All files / src/functions add.action.routes.ts

19.04% Statements 4/21
0% Branches 0/7
0% Functions 0/3
20% Lines 4/20

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    1x             1x   1x   1x                                                              
'use strict';
 
import {each, isArray} from 'lodash';
 
import {FastifyInstance} from 'fastify';
import {IncomingMessage, Server, ServerResponse} from 'http';
import {Http2Server, Http2ServerRequest, Http2ServerResponse} from 'http2';
 
import {ActionAsControllerInterface} from '@owservable/actions';
import {listSubfoldersFilesByFolderName} from '@owservable/folders';
 
import RoutesMap from '../routes.map';
 
export default async function addActionRoutes(
	fastify: FastifyInstance<Server, IncomingMessage, ServerResponse> | FastifyInstance<Http2Server, Http2ServerRequest, Http2ServerResponse>,
	root: string,
	folderName: string,
	verbose: boolean = false
): Promise<void> {
	const actionPaths: string[] = listSubfoldersFilesByFolderName(root, folderName);
 
	for (const actionPath of actionPaths) {
		Iif (verbose) console.log('[@owservable/fastify-auto-routes] -> Initializing route', actionPath);
 
		// tslint:disable-next-line:callable-types
		const ActionClass: {new (): ActionAsControllerInterface} = require(actionPath).default;
		const action: ActionAsControllerInterface = new ActionClass();
 
		Iif (typeof action.routes === 'function' && typeof action.asController === 'function') {
			const config = await action.routes();
			if (isArray(config)) {
				each(config, (conf) => {
					conf.handler = action.asController;
					fastify.route(conf);
					RoutesMap.add(conf.method, conf.url);
				});
			} else {
				config.handler = action.asController;
				fastify.route(config);
				RoutesMap.add(config.method, config.url);
			}
		}
	}
}