elysiajs / stream

Plugin for Elysia for streaming response and Server Sent Event
MIT License
15 stars 2 forks source link

handle closed connection #6

Open david-plugge opened 1 year ago

david-plugge commented 1 year ago

When the client closes the connection, the server maybe has to do something like clearing an interval.

app.get('/live', () => {
    return new Stream(async (stream) => {
        setInterval(() => {
            stream.send('hello')
        }, 1000)
    })
})

How am i supposed to achive that with the current version? I´d expect to be able to return a callback that will be called when the connection is closed to handle such stuff.

ajit283 commented 1 year ago

Ok, I found out how to do it now: you need to take the raw Request object from the context of the function (https://elysiajs.com/concept/handler.html#context) and add an eventListener to it:

request.signal.addEventListener("abort", () => {
        console.log("closed");
      });
VaronLaStrauss commented 8 months ago

To be more precise, we could use a custom function like so:

function signalCb(this: AbortSignal, ev: Event) {
   sub.unsubscribe(); // perform unsubscribe from subscribed things
   stream.close(); 
   this.removeEventListener("abort", signalCb); // yes, I am scared
}
request.signal.addEventListener("abort", signalCb, { once: true });
bogeychan commented 4 months ago

Blocked by https://github.com/elysiajs/stream/issues/10