urlpattern icon indicating copy to clipboard operation
urlpattern copied to clipboard

Expose the groups keys in patterns

Open posva opened this issue 4 years ago • 2 comments

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.

posva avatar Nov 10 '21 10:11 posva

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

wanderview avatar Nov 10 '21 13:11 wanderview

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)

posva avatar Nov 10 '21 13:11 posva