mswjs / source

Generate MSW request handlers from various sources (HAR files, OpenAPI documents, etc).
https://source.mswjs.io
134 stars 5 forks source link

HAR: Respect query parameters #45

Closed kettanaito closed 2 months ago

kettanaito commented 2 months ago

MSW removes query parameters from request URLs. We need to take those into account during the request handler generation. Most likely, to create a custom predicate with a order-insensitive match for the query parameters.

Current behavior

If the recorded traffic contains requests with query parameters, those will be stripped away by MSW (intended behavior). However, they must be respected in order to match the right requests in the generated handlers.

Expected behavior

If the recorded request has query parameters, those are translated into a predicate function within the response resolver that only matches the same requests in tests/runtime.

Note: Query parameters order should not matter.

// someplace/in/the/generator.js

const recordedRequestUrl = new URL(entry.request.url)
new HttpHandler(method, url, ({ request }) => {
  // If the recorded request has query parameters and the 
  // intercepted request doesn't match them all, skip it. 
  if (recordedRequestUrl.search && !matchesQueryParameters(request, recordedRequestUrl.searchParams)) {
    return
  }
})
weyert commented 2 months ago

That's a good one!

kettanaito commented 2 months ago

This is somewhat related to https://github.com/mswjs/msw/issues/1804. If the mentioned API is implemented on MSW's side, we should use it for query parameter predicates. The idea behind a new API is to allow the developer to introduce request predicates before the parsing phase of the request handler. This yields better performance.

But we shouldn't wait for that one to land. We can implement the predicate within the response resolver for now, that will also work.

@weyert, please, would you be interested in tackling this task? I will help with the code reviews and seeing it released. Let me know!

weyert commented 2 months ago

@weyert, please, would you be interested in tackling this task? I will help with the code reviews and seeing it released. Let me know!

Sure, I can have a look in the coming days. I have to complete some work stuff first.

kettanaito commented 2 months ago

Released: v0.2.0 🎉

This has been released in v0.2.0!

Make sure to always update to the latest version (npm i @mswjs/source@latest) to get the newest features and bug fixes.


Predictable release automation by @ossjs/release.