Skip to content

Commit

Permalink
fix(sse): prevent onClosed from firing twice in EventStream (#704)
Browse files Browse the repository at this point in the history
  • Loading branch information
joshmossas authored Jun 19, 2024
1 parent 6499059 commit 624c2cb
Show file tree
Hide file tree
Showing 4 changed files with 5 additions and 10 deletions.
5 changes: 2 additions & 3 deletions docs/1.guide/6.websocket.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,10 +100,9 @@ router.get(
await eventStream.push("Hello world");
}, 1000);

// cleanup the interval and close the stream when the connection is terminated
eventStream.onClosed(async () => {
// cleanup the interval when the connection is terminated or the writer is closed
eventStream.onClosed(() => {
clearInterval(interval);
await eventStream.close();
});

return eventStream.send();
Expand Down
5 changes: 2 additions & 3 deletions examples/server-sent-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,9 @@ router.get(
await eventStream.push("Hello world");
}, 1000);

// cleanup the interval and close the stream when the connection is terminated
eventStream.onClosed(async () => {
// cleanup the interval when the connection is terminated or the writer is closed
eventStream.onClosed(() => {
clearInterval(interval);
await eventStream.close();
});

return eventStream.send();
Expand Down
2 changes: 0 additions & 2 deletions src/utils/sse/event-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,9 @@ export class EventStream {
/**
* Triggers callback when the writable stream is closed.
* It is also triggered after calling the `close()` method.
* It also triggers when the request connection has been closed by either the client or the server.
*/
onClosed(cb: () => any) {
this._writer.closed.then(cb);
this._h3Event.node?.req.on("close", cb);
}

async send() {
Expand Down
3 changes: 1 addition & 2 deletions test/sse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ describe("Server Sent Events (SSE)", () => {
}
eventStream.push("hello world");
});
eventStream.onClosed(async () => {
await eventStream.close();
eventStream.onClosed(() => {
clearInterval(interval);
});
return eventStream.send();
Expand Down

0 comments on commit 624c2cb

Please sign in to comment.