trpc-openapi icon indicating copy to clipboard operation
trpc-openapi copied to clipboard

Add support for streaming

Open arcticfly opened this issue 2 years ago • 0 comments

Fixes #429

tRPC is really awesome, but it currently doesn't support or allow server-sent events. This small PR doesn't affect behavior for existing supported requests, but does allow a route to return a readable stream, whose events will be piped to the client.

With this change, routes will be able to return streams and pipe events through like so:

const responseStream = new TransformStream();
const writer = responseStream.writable.getWriter();
const encoder = new TextEncoder();

void writer.write(encoder.encode(JSON.stringify(chunk1)));

// Send one chunk every second for 5 seconds
let count = 0;
const interval = setInterval(() => {
  void writer.write(encoder.encode(JSON.stringify(chunk2)));
  if (count++ === 5) {
    void writer.close();
    clearInterval(interval);
  }
}, 1000);

return responseStream.readable;

arcticfly avatar Dec 20 '23 06:12 arcticfly