mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
15.93k stars 517 forks source link

Support for RFC 6570 (curly braces) path params #1558

Closed jrencz closed 1 year ago

jrencz commented 1 year ago

Scope

Improves an existing behavior

Compatibility

Feature description

On https://mswjs.io/docs/basics/request-matching#path-with-parameters it's described that one can use colon-style path params like https://api.backend.dev/user/:userId

There's http://tools.ietf.org/html/rfc6570 which defines different style of param placeholders in path. According to that spec's style the url would look like that: https://api.backend.dev/user/{userId}

For simple cases converting RFC-style placeholders to those supported by msw seems o be as simple as:

const convertPlaceholderStyle = (input: string): string =>  input.replace(/{(\w+)}/g, ':$1')

but I didn't check if it covers all cases (it covers mine).

It came to my mind that it would be nice if msw supported that style of placeholders out of the box

kettanaito commented 1 year ago

Hi, @jrencz. Thanks for proposing this.

MSW is aiming in the direction of the URIPattern specification, which is a standard that already ships in modern browsers. I understand there are different consensuses around defining request paths but we are not meaning to support all of them. The request paths you write with MSW are based off path-to-regexp that also lies in the core of the URIPattern API. That seems to be a widely accepted standard of defining paths in JavaScript.

I assume your need for a different path parameter syntax may arise when generating handlers out of external API specifications written in different standard, is that correct? In that case, you can tackle the syntax difference by introducing a path transformer function just like you've mentioned above. MSW cannot account for all possible syntaxes so a user-written transformation layer is the way to go here.

jrencz commented 1 year ago

Ok, it's clear.

I didn't know that one. I will dig deeper - it's probably a wiser choice than URI Template for my use case anyway.

Anyway it may be a good idea to link to this concept/spec on a docs page (apologies, if it's there already, I haven't noticed)

kettanaito commented 1 year ago

A good call. I will take a note to mention this in the upcoming docs rewrite, thanks!

jrencz commented 1 year ago

It seems like for now URLPattern is not for my use case. At least until https://github.com/WICG/urlpattern/issues/73 gets resolved.

Worth taking a look:

So - for now I'll stay with RFC 6570, and once there's generate in URLPattern I will be able to switch to colon-style for both uses. Until then, since my case is really simple, I'll stick to using URI.Template for generation of paths (my "production" case is not matching, routing. It's "filling in the blanks" in template for api endpoint)