Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle multi-line data while composing SSE #250

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/server/event-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ export function eventStream(

function send({ event = "message", data }: SendFunctionArgs) {
controller.enqueue(encoder.encode(`event: ${event}\n`));
controller.enqueue(encoder.encode(`data: ${data}\n\n`));

const lines = data.split("\n");
const dataLines = lines.map((line) => `data: ${line}`).join("\n");

controller.enqueue(encoder.encode(`${dataLines}\n\n`));
}

let cleanup = init(send, close);
Expand Down
14 changes: 12 additions & 2 deletions test/server/event-stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ describe(eventStream, () => {
let controller = new AbortController();
let response = eventStream(controller.signal, (send, _) => {
send({ data: "hello" });
send({ event: "multi-line", data: "hello\nworld" });
return () => {};
});

Expand All @@ -36,12 +37,21 @@ describe(eventStream, () => {
if (!response.body) throw new Error("Response body is undefined");

let reader = response.body.getReader();
let decoder = new TextDecoder();

let { value: event } = await reader.read();
expect(event).toEqual(new TextEncoder().encode("event: message\n"));
expect(decoder.decode(event)).toEqual("event: message\n");
Copy link
Author

@atesgoral atesgoral Oct 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using a decoder on the actual value instead of using an encoder on the expected value gives human-readable diffs of strings. It's very hard to understand what's wrong by looking at the Int8 array diff.


let { value: data } = await reader.read();
expect(data).toEqual(new TextEncoder().encode("data: hello\n\n"));
expect(decoder.decode(data)).toEqual("data: hello\n\n");

let { value: multiLineEvent } = await reader.read();
expect(decoder.decode(multiLineEvent)).toEqual("event: multi-line\n");

let { value: multiLineData } = await reader.read();
expect(decoder.decode(multiLineData)).toEqual(
"data: hello\ndata: world\n\n",
);

let { done } = await reader.read();
expect(done).toBe(true);
Expand Down