From ee3604bcf78d6a04dfed7525d5dd768bc99b15db Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 23 Mar 2025 11:40:02 +0000 Subject: feat(router): Add support for dynamic route parameters - Enhanced the `add` method to handle parameterized routes (e.g., `/test/:name`) by converting `:param` into regex groups. - Updated the `route` method to extract and store route parameters in the `parameters` property. - Added logic to match parameterized routes and pass extracted parameters to handlers. - Included a fallback for 404 responses when no route matches. This update allows handlers to access dynamic route parameters via `router.parameters`. --- source/index.js | 8 ++++++++ source/library/router.js | 26 ++++++++++++++++++++++---- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/source/index.js b/source/index.js index bed631f..7a2ac91 100644 --- a/source/index.js +++ b/source/index.js @@ -83,6 +83,14 @@ export default { }); }); + router.add("/test/:name", (request) => { + const { name } = router.parameters; + + return router.respond({ + message: `Hello, ${name}! :3`, + }); + }); + return router.route(); }, }; diff --git a/source/library/router.js b/source/library/router.js index 821f84a..d0914ff 100644 --- a/source/library/router.js +++ b/source/library/router.js @@ -13,6 +13,7 @@ export default class Router { this.environment = environment; this.context = context; this.routes = new Map(); // Use Map for faster lookups + this.parameters = {}; // Store extracted route parameters } /* @@ -32,7 +33,14 @@ export default class Router { } const normalizedPath = path.replace(/\/+$/, ""); // Normalize path - this.routes.set(normalizedPath, handler); + const pathRegex = new RegExp( + "^" + + normalizedPath + .replace(/:[^/]+/g, "([^/]+)") // Convert :param to regex group + .replace(/\//g, "\\/") + + "$" + ); + this.routes.set(pathRegex, { handler, originalPath: normalizedPath }); return this; } @@ -63,10 +71,20 @@ export default class Router { const url = new URL(this.request.url); const normalizedPath = url.pathname.replace(/\/+$/, ""); // Remove trailing slashes - const handler = this.routes.get(normalizedPath); + for (const [pathRegex, { handler, originalPath }] of this.routes) { + const match = normalizedPath.match(pathRegex); + if (match) { + // Extract parameters + const paramNames = [...originalPath.matchAll(/:([^/]+)/g)].map( + (m) => m[1] + ); + this.parameters = paramNames.reduce((params, name, index) => { + params[name] = match[index + 1]; + return params; + }, {}); - if (handler) { - return handler(this.request, this.environment, this.context); + return handler(this.request, this.environment, this.context); + } } // Return 404 if route not found -- cgit v1.2.3