Skip to content

Support onCleanup callback to schedule side effect cleanup when resolvers are finished #2630

Description

@piotr-cz

Scope

Improves an existing behavior

Compatibility

  • This is a breaking change

Feature description

Events pushed with client.send are being logged in DevTools console even when the request is terminated/ finished (either by ServerSentEventClient or an app)

Example

I'm using client.send method to emit ping events in a fixed interval.

I'd like to test connection recovery in case of network issues either by client.close() or client.error().

When connection is terminated using one of above methods, my app opens new connection.
In DevTools console I can see new ping events reported for new and each terminated connection.

Proposed solutions

There could be a way to notify SSE handler that connection has been terminated, so it may stop sending events or perform any other cleanups.

import { sse } from 'msw'

const handler = sse('/stream', ({ client, request }) => {
  // Schedule ping
  const pingTimer = setInterval(() => client.send({ event: 'ping', data: null }), 60_000)

  const cleanup = () => clearInterval(pingTimer)

  // Cleanup using request.signal
  request.signal.addEventListener('abort', cleanup)

  // Cleanup using client.onabort
  client.onabort = () => cleanup

  // Cleanup using returned function
  return cleanup
})

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions