whatwg / urlpattern

URL Pattern Standard
https://urlpattern.spec.whatwg.org/
Other
159 stars 22 forks source link

Expose the groups keys in patterns #147

Open posva opened 3 years ago

posva commented 3 years ago

When creating a pattern like new URLPattern('/:id/static/:tags*'), there is no way of knowing what groups the pattern has (id and tags) nor their nature (optional, repeatable).

I propose a way of getting these groups:

const pattern = new URLPattern('/:id/static/:tags*')

pattern.pathname.value // '/:id/static/:tags*'
pattern.pathname.groups // { id: { optional: false, repeatable: false }, tags: { optional: true, repeatable: true }}
// or maybe with flags
const GROUP_REPEATABLE = 1
const GROUP_OPTIONAL = 2
const GROUP_REPEATABLE_OPTIONAL = GROUP_REPEATABLE & GROUP_OPTIONAL
pattern.pathname.groups // { id: 0, tags: 3 }

It's also worth noting this can be typed in TS too with string literals.

wanderview commented 3 years ago

Interesting idea, but I must admit I don't understand what this would be used for. Can you describe the use case? Thanks.

posva commented 3 years ago

I would consider this useful for error reporting and inspecting purposes. For example, if a user tries to build a path by passing an object of groups to the pattern (which I believe must be another issue somewhere but doing pattern.buildURL({ id: 2 }) -> /2/static), we can check any missing params and give the user better debugging information. It can also be used to build UI around URL builders or checkers. For instance, I rely on this on the Vue Devtools.

Overall, this information would be very useful to extend the URLPattern API and would avoid hacks with Regexps to parse existing groups (which would partially defeat the purpose of URLPattern)