Skip to content

Commit

Permalink
fix: edge case when user (or server) sends headers before first event…
Browse files Browse the repository at this point in the history
… is sent

Signed-off-by: Marin Petrunic <[email protected]>
  • Loading branch information
mpetrunic committed Jul 25, 2023
1 parent 470b474 commit b859f3f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ export const plugin: FastifyPluginAsync<SsePluginOptions> = async function (
if (isAsyncIterable(source)) {
return handleAsyncIterable(this, source);
} else {
if (!this.sseContext?.source) {
this.sseContext = { source: pushable<EventMessage>() };
handleAsyncIterable(this, this.sseContext.source);
}
this.sseContext.source.push(source);
return;
}
Expand Down
21 changes: 21 additions & 0 deletions test/fastify4/fastify4.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,27 @@ describe("Fastify - Test SSE plugin", function () {

});

it("should send event after headers has been sent by user", function (done) {
const handler: RouteHandler = async (req, resp): Promise<void> => {
resp.header("Content-Type", "text/event-stream");
resp.raw.flushHeaders();
resp.sse({id: "1", event: "message", data: "Something"});
return resp;
};
getFastifyServer(handler).then((server2) => {
const eventsource = getEventSource(server2);
eventsource.onmessage = (evt => {
expect(evt.data).equal("Something");
expect(evt.type).equal("message");
expect(evt.lastEventId).equal("1");
eventsource.close();
server2.close();
done();
});
});

});

it("should send multiple events", function (done) {
const eventsource = getEventSource(server);
source.push({id: "1", event: "message", data: "Something"});
Expand Down

0 comments on commit b859f3f

Please sign in to comment.