cloudflare-worker-router icon indicating copy to clipboard operation
cloudflare-worker-router copied to clipboard

Nested routes

Open richardwillars opened this issue 3 years ago • 2 comments

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

richardwillars avatar Jun 30 '22 22:06 richardwillars

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 :)

tsndr avatar Oct 02 '22 22:10 tsndr

+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

syonfox avatar Sep 22 '23 17:09 syonfox