add method to route

This commit is contained in:
Lee 2023-11-20 11:04:24 +00:00
parent 4afd3a2c84
commit c89fdacafa
3 changed files with 42 additions and 2 deletions

@ -5,6 +5,7 @@ export default class TestRoute extends Route {
constructor() {
super({
path: "/test",
method: "GET",
});
}

@ -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;
}
}

@ -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}`);