mswjs / socket.io-binding

Binding to mock Socket.IO connections with Mock Service Worker.
https://mswjs.io/docs/basics/handling-websocket-events
4 stars 1 forks source link

Support preventing default for server-to-client message forwarding #1

Closed kettanaito closed 9 months ago

kettanaito commented 9 months ago

If the connection to the actual server is established by calling server.connect() (mixed interception mode), the interceptor automatically forwards all incoming server events to the client.

That forwarding can be prevented in the raw interceptor usage by calling event.preventDefault() on the wanted message event:

interceptor.on('connection', ({ client, server }) => {
  server.connect()
  server.on('message', (event) => {
    if (event.data === 'hello') {
      // Prevent forwarding this message to the client.
      event.preventDefault()
      // Instead, send a mocked message to the client
      // when the original server sends "hello".
      client.send('greetings')
    }
  })
})

What

Support server-to-client message forwarding cancellation in this wrapper too.

Challenge

The main difficulty is that the wrapper models itself after the Socket.IO API, meaning that the event listener accepts the list of all the data passed to that event:

const { server } = toSocketIoConnection({ client, server })

server.on('message', (data, a, b, c) => {
  //                  ^^^^^^^^^^^^^ all are data!
  // No access to the original MessageEvent to prevent default!
})

Need to design an API to expose the raw MessageEvent instance behind the decoded Socket.IO message so the developer can call event.preventDefault() to prevent the message forwarding.

Ideas

Expose event on listener's context

listener.bind({ event }, ...args)
server.on('message', (...data) => {
  this.event.preventDefault()
})
server.on('hello', (...data) => {
  this.event.preventDefault()
})