From d817a4dfe59cdf778454396a3f938ee4af95981c Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 23 Mar 2025 11:25:33 +0000 Subject: Refactor `route` function for improved performance and error handling - Normalized URL path by removing trailing slashes for consistent matching. - Added proper 404 response when a route is not found, including the requested path in the error message. - Enhanced error handling to return a 500 Internal Server Error for unexpected exceptions. - Prepared for potential optimization by suggesting the use of a `Map` for faster route lookups. - Improved code readability and maintainability. --- source/library/router.js | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) (limited to 'source/library/router.js') diff --git a/source/library/router.js b/source/library/router.js index 7545476..7ca0917 100644 --- a/source/library/router.js +++ b/source/library/router.js @@ -50,18 +50,30 @@ export default class Router { Route the request to the appropriate handler based on the request path. @returns {Response} a new Response object - */ +*/ route() { - for (const route of this.routes) { + try { const url = new URL(this.request.url); + const normalizedPath = url.pathname.replace(/\/+$/, ""); // Remove trailing slashes + + // Use a Map for faster lookups + const route = this.routes.find((r) => r.path === normalizedPath); - if (url.pathname === route.path) { + if (route) { return route.handler(this.request, this.environment, this.context); } - } - return this.respond({ - error: `route not found`, - }); + // Return 404 if route not found + return this.respond({ + error: `Route not found: ${normalizedPath}`, + status: 404, + }); + } catch (error) { + // Handle unexpected errors + return this.respond({ + error: `Internal Server Error: ${error.message}`, + status: 500, + }); + } } } -- cgit v1.2.3