Quellcode durchsuchen

introduce a very basic routing

Richard Köhl vor 2 Jahren
Ursprung
Commit
c4d3052a86

+ 3 - 3
deno.jsonc

@@ -1,12 +1,12 @@
 {
   "imports": {
-    "application/": "./src/application/",
+    "app/": "./src/application/",
     "domain/": "./src/domain/",
-    "infrastructure/": "./src/infra/",
+    "infra/": "./src/infrastructure/",
     "std/": "https://deno.land/std@0.191.0/"
   },
   "tasks": {
-    "dev": "deno run --allow-read --allow-env --allow-net ./src/main.ts",
+    "dev": "deno run --watch --allow-read --allow-env --allow-net ./src/main.ts",
     "test": "deno test ./test/test.ts"
   },
   "lint": {

+ 4 - 0
src/application/controllers/index.ts

@@ -0,0 +1,4 @@
+import rootController from 'app/controllers/root.controller.ts';
+import notFoundController from 'app/controllers/not-found.controller.ts';
+
+export default [rootController, notFoundController];

+ 7 - 0
src/application/controllers/not-found.controller.ts

@@ -0,0 +1,7 @@
+export default {
+  path: '*',
+  method: '*',
+  handler: (_req: Request) => {
+    return new Response('Not Found', { status: 404 });
+  },
+};

+ 8 - 0
src/application/controllers/root.controller.ts

@@ -0,0 +1,8 @@
+export default {
+  path: '/',
+  method: 'GET',
+  handler: (_req: Request) => {
+    const body = new TextEncoder().encode(Deno.env.get('GREETING'));
+    return new Response(body);
+  },
+};

+ 14 - 0
src/application/router.ts

@@ -0,0 +1,14 @@
+import controllers from './controllers/index.ts';
+
+export const router = (req: Request) => {
+  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);
+    }
+  }
+  return new Response('Not Found', { status: 404 });
+};

+ 2 - 6
src/main.ts

@@ -1,10 +1,6 @@
 import { serve } from './deps.ts';
+import { router } from 'app/router.ts';
 
 if (import.meta.main) {
-  const handler = (_req: Request) => {
-    const body = new TextEncoder().encode(Deno.env.get('GREETING'));
-    return new Response(body);
-  };
-
-  serve(handler, { port: 1993 });
+  serve(router, { port: 1993 });
 }