瀏覽代碼

optimize controller lookup in router

Richard Köhl 2 年之前
父節點
當前提交
c6ee5805e4
共有 1 個文件被更改,包括 16 次插入8 次删除
  1. 16 8
      src/interfaces/router.ts

+ 16 - 8
src/interfaces/router.ts

@@ -1,18 +1,26 @@
 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,
+    ]
+  ),
+);
+
 export const router = (req: Request) => {
   try {
     const url = new URL(req.url);
-    for (const controller of controllers) {
-      if (
-        (controller.path === '*' || controller.path === url.pathname) &&
-        (controller.method === '*' || controller.method === req.method)
-      ) {
-        return controller.handler(req);
-      }
+    const handler = controllerMap.get(`${url.pathname}:${req.method}`);
+
+    if (handler) {
+      return handler(req);
+    } else {
+      return ControllerErrors.NotFound.handler(req);
     }
-    return ControllerErrors.NotFound.handler(req);
   } catch (error: unknown) {
     return ControllerErrors.InternalServerError.handler(
       req,