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

pathToRegexp returns array with extra elements when used with optional path parts #339

Closed
esaborg opened this issue Nov 26, 2024 · 2 comments

Comments

@esaborg
Copy link

esaborg commented Nov 26, 2024

Keys array returned form pathToRegexp has unexpected entries when path has optional parts.

const { regexp, keys } = pathToRegexp(`/:one/:two/:three`);
// keys: (as exptected)
// [
//    { type: 'param', name: 'one' },
//    { type: 'param', name: 'two' },
//    { type: 'param', name: 'three' }
//  ]

When one part is changed to optional, keys array unexpectedly grows. I'd expect both cases to return keys array with 3 entries.

const { regexp, keys } = pathToRegexp(`/:one{/:two}/:three`);
// keys:
// [
//    { type: 'param', name: 'one' },
//    { type: 'param', name: 'two' },
//    { type: 'param', name: 'three' },
//    { type: 'param', name: 'one' },
//    { type: 'param', name: 'three' }
//  ]
@blakeembrey
Copy link
Member

This is by design, the keys match the result of the regexp. I can open a PR to document this but I'd recommend using match instead.

@mxngls
Copy link

mxngls commented Jan 6, 2025

@blakeembrey would you mind elaborating on the imperative behind that design decision? As a user this seems quite unintuitive. A more ergonomic API instead, might be to include the optional parameter with it's proper type i.e group and the remaning parameters thus only once. Currently keys can be a wildcard or a parameter, but there's no indication of which parameters might be optional. The naive approach would be parsing the array of keys and look for repeated keys to infer which keys might be optional. This seems quite error prone to be honest.

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

No branches or pull requests

3 participants