add route logging and a generic error handler for routes

This commit is contained in:
Lee 2023-11-20 15:42:08 +00:00
parent 35d78dc617
commit 415b9f8928
2 changed files with 63 additions and 1 deletions

48
src/route/messages.ts Normal file
View File

@ -0,0 +1,48 @@
/**
* Creates the base message for web responses
*
* @param message the message to send
* @returns the message
*/
function baseMessage(error: boolean, message: string) {
return {
error,
message,
};
}
/**
* Creates an error message for web responses
*
* @param message the message to send
* @returns the message
*/
function errorMessage(message: string) {
return baseMessage(true, message);
}
/**
* Creates a success message for web responses
*
* @param message the message to send
* @returns the message
*/
function successMessage(message: string) {
return baseMessage(false, message);
}
/**
* Creates a message for an internal server error
*
* @returns the message
*/
function internalServerError() {
return errorMessage("Internal Server Error");
}
export const ServerMessages = {
baseMessage,
errorMessage,
successMessage,
internalServerError,
};

View File

@ -1,4 +1,5 @@
import express, { Express } from "express";
import { ServerMessages } from "../route/messages";
import { Route } from "../route/route";
type ServerConfig = {
@ -32,13 +33,26 @@ export default class Server {
this.server = express();
this.preInit();
// Setup route logging
this.server.use((req, res, next) => {
// TODO: make this look better?
console.log(`[${req.method}] ${req.path}`);
next();
});
// Handle the routes
for (const route of this.routes) {
this.server.all(route.getPath(), (req, res, next) => {
if (req.method.toUpperCase() !== route.getMethod().toUpperCase()) {
return next(); // Skip this method
}
route.handle(req, res, next);
try {
route.handle(req, res, next);
} catch (ex) {
console.error(ex);
// Inform the user that an internal server error occurred
res.status(500).json(ServerMessages.internalServerError());
}
});
}