advent-of-code

Entries to advent of code, multiple years
git clone git://git.finwo.net/misc/advent-of-code
Log | Files | Refs

index.ts (1533B)


      1 import { Request, Response } from 'express';
      2 import { Container } from 'typedi';
      3 
      4 const routes      = new Map();
      5 const controllers = [];
      6 
      7 export enum Method {
      8   DELETE = 'delete',
      9   GET    = 'get',
     10   POST   = 'post',
     11   PUT    = 'put',
     12 };
     13 
     14 export function Controller(prefix?: string): ClassDecorator {
     15   return function(constructor: Function) {
     16     const router           = Container.get('router');
     17     const controllerRoutes = routes.get(constructor) || [];
     18     for(const route of controllerRoutes) {
     19       const path = ['',prefix,route.path].join('/').replace(/\/+/g,'/');
     20       router[route.method](path, async (req: Request, res: Response, next: Function) => {
     21         const controller = Container.get(constructor);
     22         await controller[route.name]({ req, res, ...req.params });
     23         if (!res.writableEnded) next();
     24       });
     25     }
     26   }
     27 }
     28 
     29 export function Route(method: Method, path: string): MethodDecorator {
     30   return function(target: any, propertyKey: string, descriptor: PropertyDescriptor): void {
     31     const map = routes.get(target.constructor) || [];
     32     map.push({ path, method, name: propertyKey });
     33     routes.set(target.constructor, map);
     34   };
     35 }
     36 
     37 export function Delete(path: string): MethodDecorator {
     38   return Route(Method.DELETE, path);
     39 }
     40 
     41 export function Get(path: string): MethodDecorator {
     42   return Route(Method.GET, path);
     43 }
     44 
     45 export function Post(path: string): MethodDecorator {
     46   return Route(Method.POST, path);
     47 }
     48 
     49 export function Put(path: string): MethodDecorator {
     50   return Route(Method.PUT, path);
     51 }