engine.io-parser icon indicating copy to clipboard operation
engine.io-parser copied to clipboard

Expose synchronous "encodePacket" function

Open kettanaito opened this issue 1 year ago • 0 comments
trafficstars

Currently, the encodePacket function always returns the result in its callback argument. I understand that's likely done to prevent blocking the thread in some situations.

I'd like to propose exporting a new function that'd be Packet -> string.

function encodePacketInline(
  packet: Packet,
  supportsBinary: boolean
): string

The name is illustrational. I'm open to suggestions.

I'd like to use such a function in my custom message parser:

client.on('message', (event) => {
  server.send(
    encodePacketInline({
      type: 'message',
      data: encoder.encode({ type: 2, data: ['message', 'payload'], nsp: '/' })
    })
  )
})

This is intentionally simplified example of my setup. In reality, I have a transport.parser instance that automatically wraps outgoing events to the server in transport.parser.encode(data) before providing the payload to the MessageEvent. This is also code that the consumer of my library is intended to write (their own parser).

How?

The logic for encoding is already synchronous:

https://github.com/socketio/engine.io-parser/blob/23213858c6b312b3a4533dcf6be654fbf8012934/lib/encodePacket.ts#L10

https://github.com/socketio/engine.io-parser/blob/23213858c6b312b3a4533dcf6be654fbf8012934/lib/encodePacket.ts#L14

I simply propose moving it to a new standalone public function.

kettanaito avatar Jan 31 '24 19:01 kettanaito