mswjs / interceptors

Low-level network interception library.
https://npm.im/@mswjs/interceptors
MIT License
537 stars 123 forks source link

Replace "request.respondWith()" with a Controller #431

Closed kettanaito closed 2 months ago

kettanaito commented 12 months ago

Instead of adding the respondWith() custom method on the Fetch API Request representation of the intercepted request, expose that method alongside the request in the listener argument object.

interceptor.on('request', (event) => {
  const { request } = event
  event.respondWith(new Response())
})

This also resembles the Service Worker's fetch event a bit more closely. Not that it has ever the intention but it's a nice little detail.

kettanaito commented 4 months ago

Request controller interface

interface RequestController {
  // Instruct the interceptor to perform the request as-is.
  passthrough(): void

  // Use the given response as the mock response for the request.
  respondWith(response: Response): void

  // Use the given error as the request error.
  errorWith(error?: Error): void

  // Abort the request.
  // In some clients (ClientRequest) it's synonymous to ".errorWith()",
  // in others (XMLHttpRequest) it's different. 
  abort(): void
}

The request controller is exposed in the request listener argument:

interceptor.on('request', ({ request, controller }) => {
  controller.respondWith(new Response('hello world'))
})

The request controller can only handle the request once. Once any of its methods are called, calling methods on it again must throw an error (the same way calling request.respondWith() multiple times right now throws an error).

kettanaito commented 2 months ago

Released: v0.33.0 🎉

This has been released in v0.33.0!

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


Predictable release automation by @ossjs/release.