From c89fdacafada2724608f58a4e4729f9f6c8b6881 Mon Sep 17 00:00:00 2001 From: Liam Date: Mon, 20 Nov 2023 11:04:24 +0000 Subject: [PATCH] add method to route --- src/route/impl/testRoute.ts | 1 + src/route/route.ts | 31 ++++++++++++++++++++++++++++++- src/server/server.ts | 12 +++++++++++- 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/route/impl/testRoute.ts b/src/route/impl/testRoute.ts index 8badb9f..935a53c 100644 --- a/src/route/impl/testRoute.ts +++ b/src/route/impl/testRoute.ts @@ -5,6 +5,7 @@ export default class TestRoute extends Route { constructor() { super({ path: "/test", + method: "GET", }); } diff --git a/src/route/route.ts b/src/route/route.ts index 751cd19..1da2d68 100644 --- a/src/route/route.ts +++ b/src/route/route.ts @@ -1,17 +1,37 @@ import { Request, Response } from "express"; +type Method = "GET" | "POST" | "PUT" | "DELETE" | "ALL"; + type RouteType = { /** * The path to handle */ path: string; + + /** + * The method to handle + */ + method?: Method; }; export abstract class Route { + /** + * The path to handle + */ private path: string; - constructor({ path }: RouteType) { + /** + * The method to listen for requests on + */ + private method: Method; + + constructor({ path, method }: RouteType) { this.path = path; + if (!method) { + method = "GET"; + } + this.method = method; + console.log(`Created route handler for ${path}`); } @@ -31,4 +51,13 @@ export abstract class Route { getPath() { return this.path; } + + /** + * Get the method of the route + * + * @returns the method + */ + getMethod() { + return this.method; + } } diff --git a/src/server/server.ts b/src/server/server.ts index 542fac2..6dd98c9 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -34,10 +34,20 @@ export default class Server { // Handle the routes for (const route of this.routes) { - this.server.all(route.getPath(), (req, res) => route.handle(req, res)); + this.server.all(route.getPath(), (req, res, next) => { + if (req.method.toUpperCase() !== route.getMethod().toUpperCase()) { + return next(); // Skip this method + } + route.handle(req, res); + }); } console.log(`Registered ${this.routes.length} routes`); + // Handle unknown routes + this.server.all("*", (req, res) => { + res.status(404).send("404 Not Found"); + }); + // Start listening on the specified port this.server.listen(this.port, () => { console.log(`Server listening on port ${this.port}`);