浏览代码

allow multiple endpoints/methods per controller

Richard Köhl 2 年之前
父节点
当前提交
287793536d

+ 8 - 7
src/interfaces/controllers/controller.class.ts

@@ -9,13 +9,14 @@ interface Options {
 }
 export default class Controller {
   constructor(
-    public path: string,
-    public method: string,
-    public handler: (
-      req: Request,
-      error?: string,
-    ) => Response | Promise<Response>,
-    public headers: Record<string, string> = {},
+    public handlers: Record<
+      string,
+      (
+        req: Request,
+        error?: string,
+        headers?: Record<string, string>,
+      ) => Response | Promise<Response>
+    >,
   ) {}
 
   public static response = (

+ 9 - 9
src/interfaces/controllers/errors.controller.ts

@@ -4,19 +4,19 @@ import { logger } from 'infra/logger.ts';
 import Controller from 'if/controllers/controller.class.ts';
 
 export const ControllerErrors = {
-  NotFound: new Controller('*', '*', (req: Request) => {
-    return Controller.response(req, 'not found', {
-      status: HTTPStatus.NotFound,
-    });
+  NotFound: new Controller({
+    '*_*': (req: Request) => {
+      return Controller.response(req, 'not found', {
+        status: HTTPStatus.NotFound,
+      });
+    },
   }),
-  InternalServerError: new Controller(
-    '*',
-    '*',
-    (req: Request, error?: string) => {
+  InternalServerError: new Controller({
+    '*_*': (req: Request, error?: string) => {
       logger.error(error);
       return Controller.response(req, 'internal server error', {
         status: HTTPStatus.InternalServerError,
       });
     },
-  ),
+  }),
 };

+ 3 - 5
src/interfaces/controllers/health.controller.ts

@@ -1,9 +1,7 @@
 import Controller from 'if/controllers/controller.class.ts';
 
-export default new Controller(
-  '/health',
-  'GET',
-  (req: Request) => {
+export default new Controller({
+  '/health_GET': (req: Request) => {
     const url = new URL(req.url);
     const started = Deno.env.get('STARTED');
     let uptime = 0;
@@ -23,4 +21,4 @@ export default new Controller(
 
     return Controller.responseJSON(req, body);
   },
-);
+});

+ 3 - 5
src/interfaces/controllers/metrics.controller.ts

@@ -1,11 +1,9 @@
 import Controller from 'if/controllers/controller.class.ts';
 
-export default new Controller(
-  '/metrics',
-  'GET',
-  (req: Request) => {
+export default new Controller({
+  '/metrics_GET': (req: Request) => {
     const body = Deno.metrics();
 
     return Controller.responseJSON(req, body);
   },
-);
+});

+ 3 - 5
src/interfaces/controllers/root.controller.ts

@@ -1,9 +1,7 @@
 import Controller from 'if/controllers/controller.class.ts';
 
-export default new Controller(
-  '/',
-  'GET',
-  (req: Request) => {
+export default new Controller({
+  '/_GET': (req: Request) => {
     return Controller.response(req, Deno.env.get('GREETING') ?? '');
   },
-);
+});

+ 13 - 12
src/interfaces/router.ts

@@ -2,27 +2,28 @@ import controllers from 'if/controllers/index.ts';
 import { ControllerErrors } from 'if/controllers/errors.controller.ts';
 
 // Preprocess controllers into a map
-const controllerMap = new Map(
-  controllers.map(
-    (controller) => [
-      `${controller.path}:${controller.method}`,
-      controller.handler,
-    ]
-  ),
-);
+const controllerMap = new Map();
+for (const controller of controllers) {
+  for (const [key, handler] of Object.entries(controller.handlers)) {
+    controllerMap.set(key, handler);
+  }
+}
 
 export const router = (req: Request) => {
   try {
     const url = new URL(req.url);
-    const handler = controllerMap.get(`${url.pathname}:${req.method}`);
+    const handler = controllerMap.get(`${url.pathname}_${req.method}`);
 
     if (handler) {
-      return handler(req);
+      // Pass headers as an argument to the handler
+      return handler(req, undefined, { 'Content-Type': 'application/json' });
     } else {
-      return ControllerErrors.NotFound.handler(req);
+      // Use the handler from the NotFound controller
+      return ControllerErrors.NotFound.handlers['*_*'](req);
     }
   } catch (error: unknown) {
-    return ControllerErrors.InternalServerError.handler(
+    // Use the handler from the InternalServerError controller
+    return ControllerErrors.InternalServerError.handlers['*_*'](
       req,
       error instanceof Error ? error.message : 'unknown error!',
     );