|
|
@@ -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!',
|
|
|
);
|