Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
kettanaito opened this issue Sep 18, 2023 · 1 comment
Open

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

kettanaito opened this issue Sep 18, 2023 · 1 comment
Assignees

Comments

@kettanaito
Copy link
Member

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 kettanaito changed the title Do not modify "request" instance with "respondWith()" Replace "request.respondWith()" with a Controller Apr 26, 2024
@kettanaito
Copy link
Member Author

kettanaito commented Apr 26, 2024

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant