|
@@ -1,18 +1,26 @@
|
|
|
import controllers from 'if/controllers/index.ts';
|
|
import controllers from 'if/controllers/index.ts';
|
|
|
import { ControllerErrors } from 'if/controllers/errors.controller.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) => {
|
|
export const router = (req: Request) => {
|
|
|
try {
|
|
try {
|
|
|
const url = new URL(req.url);
|
|
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) {
|
|
} catch (error: unknown) {
|
|
|
return ControllerErrors.InternalServerError.handler(
|
|
return ControllerErrors.InternalServerError.handler(
|
|
|
req,
|
|
req,
|