cloudflare-worker-router
cloudflare-worker-router copied to clipboard
Nested routes
Just wanted to say it's a nice little library you have here, very well written.
Wondered if you've got any plans for allowing nested routes to be defined in different files? E.g if you had a route of GET /user it'd be nice if you could define that in the parent router, and instead of running the function to handle that route, it instead points it to a router in another file. Then in that file you could define child routes, E.g GET :id. This would then get setup as GET /users/:id
Hey,
This is definitely something I've been meaning to add but haven't gotten around to yet.
Thanks for letting me know that you're interested in this feature :)
+1 I use this in express to define an api in each file.
edit: I misinterpreted and ... https://github.com/tsndr/cloudflare-worker-router/blob/v3.0.0/README.md#url-string
reminder for later but this is getting close I think it can be a bit more elegant
function getRouteMatcher(path) {
const segments = path.split('/');
const regexSegments = segments.map(segment => (segment.startsWith(':') ? '([^/]+)' : segment));
const regexString = `^${regexSegments.join('\\/')}$`;
return new RegExp(regexString);
}
function matchRoute(uri, path) {
const routeMatcher = getRouteMatcher(path);
const match = uri.match(routeMatcher);
if (!match) return { matched: false };
const params = {};
path.split('/').forEach((segment, i) => {
if (segment.startsWith(':'))
console.log(segment, match, i)
//thre is a bug here with /:param1/:param2
params[segment.slice(1)] = match[i-1];
});
return { matched: true, params };
}
//https://codesandbox.io/s/stoic-austin-sx84zx?file=/src/index.mjs
https://codesandbox.io/s/stoic-austin-sx84zx?file=/src/index.mjs