All files / lib/router routes.ts

100% Statements 13/13
100% Branches 4/4
100% Functions 3/3
100% Lines 13/13

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                          1x                 1x 5x 6x 6x 1x     6x 6x                         1x         1x         1x         1x         1x
import { Controller } from './types';
 
/**
 * @interface RouteDefinition
 * @description An interface for defining a route.
 */
export interface RouteDefinition {
  path: string;
  method: 'get' | 'post' | 'put' | 'patch' | 'delete';
  action: string;
  controller?: Controller;
  contentType?: string;
}
import 'reflect-metadata';
 
/**
 * @function createRouteDecorator
 * @description A factory function for creating route decorators.
 * @param {('get' | 'post' | 'put' | 'patch' | 'delete')} method - The HTTP method.
 * @returns {((path: string, options?: { contentType: string }) => MethodDecorator)} A method decorator.
 */
const createRouteDecorator =
  (method: 'get' | 'post' | 'put' | 'patch' | 'delete') =>
  (path: string, options?: { contentType: string }): MethodDecorator => {
    return (target, propertyKey) => {
      if (!Reflect.hasMetadata('routes', target.constructor)) {
        Reflect.defineMetadata('routes', [], target.constructor);
      }
 
      const routes: RouteDefinition[] = Reflect.getMetadata('routes', target.constructor);
      routes.push({
        method,
        path,
        action: propertyKey as string,
        contentType: options?.contentType || 'application/json',
      });
    };
  };
 
/**
 * @decorator Get
 * @description A method decorator for defining a GET route.
 */
export const Get = createRouteDecorator('get');
/**
 * @decorator Post
 * @description A method decorator for defining a POST route.
 */
export const Post = createRouteDecorator('post');
/**
 * @decorator Put
 * @description A method decorator for defining a PUT route.
 */
export const Put = createRouteDecorator('put');
/**
 * @decorator Patch
 * @description A method decorator for defining a PATCH route.
 */
export const Patch = createRouteDecorator('patch');
/**
 * @decorator Delete
 * @description A method decorator for defining a DELETE route.
 */
export const Delete = createRouteDecorator('delete');