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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | 1x 1x 1x 4x 4x 4x 4x 4x 4x 2x 4x 16x 14x 6x 2x 4x 4x 4x 6x 2x 4x 1x 1x 4x 3x 3x 3x 4x 3x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 2x 1x 1x 2x 2x 2x 1x 4x 4x 4x 4x 8x 4x | import { IncomingMessage, ServerResponse } from 'http'; import { container } from '../di/di'; import { RouteDefinition } from './routes'; import { Controller, IRouterMiddleware, Next } from './types'; import { AppError, MethodNotAllowedError } from '../errors/errors'; /** * @function router * @description Creates a new router middleware. * @returns {IRouterMiddleware} The router middleware. */ export const router = (): IRouterMiddleware => { const routes: RouteDefinition[] = []; /** * @function routerMiddleware * @description The router middleware. * @param {IncomingMessage} req - The request object. * @param {ServerResponse} res - The response object. * @param {Next} next - The next middleware function. */ const routerMiddleware = ( req: IncomingMessage, res: ServerResponse, next: Next ) => { let route: RouteDefinition | undefined; let params: { [key: string]: string } = {}; let queryParams: { [key: string]: string } = {}; const url = new URL(req.url!, `http://${req.headers.host}`); url.searchParams.forEach((value, key) => { queryParams[key] = value; }); for (const r of routes) { const routeParts = r.path.split('/').filter(p => p); const urlParts = url.pathname.split('/').filter(p => p); if (routeParts.length !== urlParts.length) { continue; } let match = true; const currentParams: { [key: string]: string } = {}; for (let i = 0; i < routeParts.length; i++) { if (routeParts[i].startsWith(':')) { currentParams[routeParts[i].substring(1)] = urlParts[i]; } else if (routeParts[i] !== urlParts[i]) { match = false; break; } } if (match) { route = r; params = currentParams; break; } } if (route && route.controller) { if (route.method !== req.method?.toLowerCase()) { const error = new MethodNotAllowedError(); res.statusCode = error.statusCode; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ message: error.message })); return; } try { const controller = container.resolve(route.controller); const securityClass = Reflect.getMetadata('security', controller.constructor, route.action); Iif (securityClass) { const security = new securityClass(); security.authenticate(req); } Eif (route.contentType) { res.setHeader('Content-Type', route.contentType); } const bodyParams: number[] = Reflect.getMetadata('body', controller.constructor, route.action) || []; const validators: { index: number, validator: new () => any }[] = Reflect.getMetadata('validators', controller.constructor, route.action) || []; const pathParams: { index: number, name: string }[] = Reflect.getMetadata('pathParams', controller.constructor, route.action) || []; const queryParamsMetadata: number[] = Reflect.getMetadata('queryParams', controller.constructor, route.action) || []; const args: any[] = []; pathParams.forEach(p => { args[p.index] = params[p.name]; }); if (queryParamsMetadata.length > 0) { queryParamsMetadata.forEach(p => { args[p] = queryParams; }); } Iif (bodyParams.length > 0) { let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', () => { try { const parsedBody = JSON.parse(body); validators.forEach(v => { if (v.index === bodyParams[0]) { const validator = new v.validator(); validator.validate(parsedBody); } }); args[bodyParams[0]] = parsedBody; args.push(req, res); controller[route.action](...args); } catch (error) { if (error instanceof AppError) { res.statusCode = error.statusCode; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ message: error.message })); } else { res.statusCode = 500; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ message: 'Internal Server Error' })); } } }); } else { args.push(req, res); controller[route.action](...args); } } catch (error) { if (error instanceof AppError) { res.statusCode = error.statusCode; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ message: error.message })); } else { res.statusCode = 500; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ message: 'Internal Server Error' })); } } } else { next(); } }; /** * @method register * @description Registers a controller with the router. * @param {Controller} controller - The controller to register. */ routerMiddleware.register = (controller: Controller) => { const controllerInstance = container.resolve(controller); const controllerRoutes: RouteDefinition[] = Reflect.getMetadata('routes', controllerInstance.constructor) || []; controllerRoutes.forEach((route: RouteDefinition) => { routes.push({ ...route, controller: controllerInstance.constructor as Controller }); }); }; return routerMiddleware as IRouterMiddleware; }; |