aboutsummaryrefslogtreecommitdiff
path: root/source/library/router.js
diff options
context:
space:
mode:
authorAlex <zuedev@gmail.com>2025-03-23 11:16:14 +0000
committerAlex <zuedev@gmail.com>2025-03-23 11:16:14 +0000
commit6601749134b506a3e826b335a67d7d18d2b276d5 (patch)
treeb1f8940982bd36d2ee82f51f9d911af4d735bbdc /source/library/router.js
parent459fabf119117c2d204ea5e8f17b05a713f4514e (diff)
downloadzue.dev-6601749134b506a3e826b335a67d7d18d2b276d5.tar
zue.dev-6601749134b506a3e826b335a67d7d18d2b276d5.tar.gz
zue.dev-6601749134b506a3e826b335a67d7d18d2b276d5.tar.bz2
zue.dev-6601749134b506a3e826b335a67d7d18d2b276d5.tar.xz
zue.dev-6601749134b506a3e826b335a67d7d18d2b276d5.zip
refactor: implement Router class for improved request handling
Diffstat (limited to 'source/library/router.js')
-rw-r--r--source/library/router.js67
1 files changed, 67 insertions, 0 deletions
diff --git a/source/library/router.js b/source/library/router.js
new file mode 100644
index 0000000..7545476
--- /dev/null
+++ b/source/library/router.js
@@ -0,0 +1,67 @@
+/*
+ Router class to handle routing of requests based on the request path.
+
+ @param {Request} request - the incoming request object
+ @param {Environment} environment - the environment object
+ @param {Context} context - the context object
+
+ @returns {Response} a new Response object
+*/
+export default class Router {
+ constructor(request, environment, context) {
+ this.request = request;
+ this.environment = environment;
+ this.context = context;
+ this.routes = [];
+ }
+
+ /*
+ Add a new route to the router.
+
+ @param {string} path - the path to match
+ @param {function} handler - the handler function to call if the path matches
+
+ @returns {Router} the router object
+ */
+ add(path, handler) {
+ return this.routes.push({
+ path,
+ handler,
+ });
+ }
+
+ /*
+ Helper function to respond with a JSON object
+
+ @param {object} body - the JSON object to respond with
+
+ @returns {Response} a new Response object
+ */
+ respond(body) {
+ return new Response(JSON.stringify(body), {
+ headers: {
+ "Access-Control-Allow-Origin": "*",
+ "Content-Type": "application/json",
+ },
+ });
+ }
+
+ /*
+ 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) {
+ const url = new URL(this.request.url);
+
+ if (url.pathname === route.path) {
+ return route.handler(this.request, this.environment, this.context);
+ }
+ }
+
+ return this.respond({
+ error: `route not found`,
+ });
+ }
+}