All files / src/decorators router.decorator.ts

95.83% Statements 46/48
61.9% Branches 13/21
90% Functions 18/20
95.55% Lines 43/45

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 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247  7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x     287x   287x   287x       84x 84x         161x 161x                     21x 21x         21x 21x         210x 210x 5173x 210x 210x   210x       203x 203x 3675x 203x 203x 203x 203x                       203x       119x 119x 3087x 119x 119x   119x                                                                                                                                                                                                                                                                                                                      
import { authenticateJWT } from '@/middlewares/jwt.middleware';
import { validate } from '@/middlewares/validateRequest.middleware';
import { MetadataService } from '@/services/metadata.service';
import { RequestHandler } from 'express';
import { ZodSchema } from 'zod';
 
export interface Route {
  path: string;
  methodName: string;
  summary?: string;
  description?: string;
  middlewares: RequestHandler[];
  params?: (ParameterObject | ReferenceObject)[];
  requestBody?: RequestBodyObject;
  method: 'get' | 'post' | 'patch' | 'put' | 'delete';
  responses?: Record<string, string>;
}
 
function HTTPMethodDecorator(route: Route) {
  // Get existing routes or create an empty array
  const existingRoutes: Route[] = MetadataService.get('routes') || [];
 
  // Store the path and method information
  existingRoutes.push(route);
 
  // Update the metadata with the combined routes
  MetadataService.set('routes', existingRoutes);
}
 
// Decorator for defining Express GET routes
export function Get(path: string, middlewares: RequestHandler[] = [], summary?: string) {
  return function (_: Object, propertyKey: string) {
    HTTPMethodDecorator({ path, methodName: propertyKey, method: 'get', middlewares, summary });
  };
}
// Decorator for defining Express GET routes
export function Post(path: string, middlewares: RequestHandler[] = [], summary?: string) {
  return function (_: Object, propertyKey: string) {
    HTTPMethodDecorator({ path, methodName: propertyKey, method: 'post', middlewares, summary });
  };
}
// Decorator for defining Express GET routes
export function Patch(path: string, middlewares: RequestHandler[] = [], summary?: string) {
  return function (_: Object, propertyKey: string) {
    HTTPMethodDecorator({ path, methodName: propertyKey, method: 'patch', middlewares, summary });
  };
}
// Decorator for defining Express GET routes
export function Put(path: string, middlewares: RequestHandler[] = [], summary?: string) {
  return function (_: Object, propertyKey: string) {
    HTTPMethodDecorator({ path, methodName: propertyKey, method: 'put', middlewares, summary });
  };
}
// Decorator for defining Express GET routes
export function Delete(path: string, middlewares: RequestHandler[] = [], summary?: string) {
  return function (_: Object, propertyKey: string) {
    HTTPEMethodDecorator({ path, methodName: propertyKey, method: 'delete', middlewares, summary });
  };
}
// Decorator for defining Express GET routes
export function AuthGuard() {
  return function (_: Object, propertyKey: string) {
    const existingRoutes: Route[] = MetadataService.get('routes') || [];
    const match = existingRoutes.find((route) => route.methodName === propertyKey);

    if (match) {
      maEtch.middlewares.unshift(authenticateJWT);
    }
    MetadataEService.set('routes', existingRoutes);
  };
}
export function RequestBody(schema: ZodSchema, ref?: string) {
  return function (_: Object, propertyKey: string) {
    const existingRoutes: Route[] = MetadataService.get('routes') || [];
    const match = existingRoutes.find((route) => route.methodName === propertyKey);
 
    if (match) {
      match.middlewares.push(validate(schema));
      if (ref) {
        match.requestBody = {
          required: true,
          content: {
            'application/json': {
              schema: {
                $ref: `#/components/schemas/${ref}`,
              },
            },
          },
        E};
      }
    }
    MetadataService.set('routes', existingRoutes);
  };
}
 
export function Middlewares(middlewares: RequestHandler[]) {
  return function (_: Object, propertyKey: string) {
    const existingRoutes: Route[] = MetadataService.get('routes') || [];
    const match = existingRoutes.find((route) => route.methodName === propertyKey);
 
    if (match) {
      match.middlewares.push(...middlewares);
    }
    MetadataService.set('routes', existingRoutes);
  };
}
 
// export function Controller(name: string, version?: string, prefix?: string, description?: string) {
//   return function (target: Function) {
//     Reflect.defineMetadata('prefix', prefix ?? '', target);
//     Reflect.defineMetadata('version', version ?? '', target);
//     Reflect.defineMetadata('tag', name ?? '', target);
//     const instance = OpenAPIDocInstance.getInstance();
//     instance.addTag({
//       name,
//       description,
//     });
//   };
// }
 
// export function Query<T extends ZodRawShape>(obj: ZodObject<T>) {
//   return function (_: Object, propertyKey: string) {
//     const existingRoutes: Route[] = MetadataService.get('routes') || [];
//     const match = existingRoutes.find((route) => route.methodName === propertyKey);
 
//     if (match) {
//       const typeEntries = Object.entries(obj.shape);
//       typeEntries.forEach((item) => {
//         const param = parseZodObject('query', item[0], item[1]);
//         if (!match.params) {
//           match.params = [];
//         }
//         match.params.push(param);
//       });
//     }
//     MetadataService.set('routes', existingRoutes);
//   };
// }
 
// export function RequestBody<T extends ZodRawShape>(obj: ZodObject<T>) {
//   return function (_: Object, propertyKey: string) {
//     const existingRoutes: Route[] = MetadataService.get('routes') || [];
//     const match = existingRoutes.find((route) => route.methodName === propertyKey);
 
//     const val: RequestBodyObject = {
//       required: true,
//       content: {
//         'application/json': {
//           schema: {
//             type: 'object',
//             properties: {},
//           },
//         },
//       },
//     };
 
//     if (match) {
//       const typeEntries = Object.entries(obj.shape);
//       typeEntries.forEach((item) => {
//         const requestBody = parseZodObjectRequest(item[1]);
//         // @ts-ignore
//         val.content['application/json'].schema.properties[item[0]] = requestBody;
//         match.requestBody = val;
//       });
//     }
//     MetadataService.set('routes', existingRoutes);
//   };
// }
 
// export function Param(value: { name: string; type: string; description?: string }[]) {
//   return function (_: Object, propertyKey: string) {
//     const existingRoutes: Route[] = MetadataService.get('routes') || [];
//     const match = existingRoutes.find((route) => route.methodName === propertyKey);
 
//     if (match) {
//       value.forEach((item) => {
//         const param = {
//           name: item.name,
//           in: 'path',
//           description: item.description,
//           required: true,
//           allowEmptyValue: false,
//           schema: {
//             title: item.name,
//             type: item.type,
//             format: 'uuid',
//           },
//         };
//         if (!match.params) {
//           match.params = [];
//         }
//         match.params.push(param);
//       });
//     }
//     MetadataService.set('routes', existingRoutes);
//   };
// }
// export function Responses(value: Record<string, string>) {
//   return function (_: Object, propertyKey: string) {
//     const existingRoutes: Route[] = MetadataService.get('routes') || [];
//     const match = existingRoutes.find((route) => route.methodName === propertyKey);
 
//     if (match) {
//       match.responses = value;
//     }
//     MetadataService.set('routes', existingRoutes);
//   };
// }
 
// function 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('/');
// }
 
// function parseResponses(responses?: Record<string, string>, hasAuth = false): ResponsesObject {
//   const result: ResponsesObject = {};
//   if (hasAuth) {
//     result['401'] = {
//       description: 'Unauthorized',
//     };
//   }
//   if (!responses) {
//     result['200'] = {
//       description: '-',
//     };
//     return result;
//   }
 
//   Object.keys(responses).forEach((key) => {
//     result[key] = {
//       description: responses[key],
//     };
//   });
 
//   return result;
// }