All files / src/routes router.ts

100% Statements 34/34
90% Branches 9/10
100% Functions 5/5
100% Lines 33/33

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  7x 7x 7x 7x 7x 7x 7x     35x 35x 35x     287x 259x 28x 28x 28x 140x 140x 28x   140x   28x     287x 287x 287x                 287x 287x     35x 35x 1043x 287x 287x 287x     35x     7x                
import { parseAPIVersion } from '@/config/app.config';
import { Route } from '@/decorators/router.decorator';
import { authenticateJWT } from '@/middlewares/jwt.middleware';
import { MetadataService } from '@/services/metadata.service';
import { OpenAPIDocInstance } from '@/utils/openAPIGenerator';
import { Router } from 'express';
 
export class MainRouter {
  protected routes: Router;
 
  constructor(
    protected pathPrefix: string,
    protected tag: string
  ) {
    this.routes = Router();
  }
 
  private _parseDynamicRoute(path: string) {
    if (!path.includes(':')) return path;
    const dynamicParts = path.split('/');
    const newPath = [];
    for (let index = 0; index < dynamicParts.length; index++) {
      let part = dynamicParts[index];
      if (part.includes(':')) {
        part = `{${part.replace(/:/g, '')}}`;
      }
      newPath.push(part);
    }
 
    return newPath.join('/');
  }
 
  private _registerOpenApiPath(route: Route) {
    const instance = OpenAPIDocInstance.getInstance();
    const pathElement: PathItemObject = {};
 
    pathElement[route.method] = {
      summary: route.summary,
      operationId: `${parseAPIVersion(1)}/${route.methodName}`,
      parameters: route.params,
      requestBody: route.requestBody,
      responses: {},
      security: route.middlewares.includes(authenticateJWT) ? [{ bearerAuth: [] }] : [],
      tags: [this.tag],
    };
    const swaggerPath = this._parseDynamicRoute(this.pathPrefix + route.path);
    instance.addPath(swaggerPath, pathElement);
  }
 
  getRoute(controllerClass: any) {
    const existingRoutes: Route[] = MetadataService.get('routes') || [];
 
    existingRoutes.forEach((route: Route) => {
      if (route.methodName in controllerClass) {
        const handler: Function = controllerClass[route.methodName as keyof typeof controllerClass];
        this.routes[route.method](route.path, ...route.middlewares, handler.bind(controllerClass));
        this._registerOpenApiPath(route);
      }
    });
 
    return this.routes;
  }
}