aboutsummaryrefslogtreecommitdiff
path: root/source
diff options
context:
space:
mode:
authorAlex <zuedev@gmail.com>2025-03-23 11:25:33 +0000
committerAlex <zuedev@gmail.com>2025-03-23 11:25:33 +0000
commitd817a4dfe59cdf778454396a3f938ee4af95981c (patch)
tree22b4e9a3f5d5202f62569219ce1aa5dec1f29d8c /source
parent6601749134b506a3e826b335a67d7d18d2b276d5 (diff)
downloadzue.dev-d817a4dfe59cdf778454396a3f938ee4af95981c.tar
zue.dev-d817a4dfe59cdf778454396a3f938ee4af95981c.tar.gz
zue.dev-d817a4dfe59cdf778454396a3f938ee4af95981c.tar.bz2
zue.dev-d817a4dfe59cdf778454396a3f938ee4af95981c.tar.xz
zue.dev-d817a4dfe59cdf778454396a3f938ee4af95981c.zip
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.
Diffstat (limited to 'source')
-rw-r--r--source/library/router.js26
1 files changed, 19 insertions, 7 deletions
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,
+ });
+ }
}
}