Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested routes #20

Open
richardwillars opened this issue Jun 30, 2022 · 2 comments
Open

Nested routes #20

richardwillars opened this issue Jun 30, 2022 · 2 comments
Labels
enhancement New feature or request

Comments

@richardwillars
Copy link

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

@tsndr
Copy link
Owner

tsndr commented Oct 2, 2022

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 tsndr added the enhancement New feature or request label Oct 3, 2022
@syonfox
Copy link

syonfox commented Sep 22, 2023

+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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants