-
-
Notifications
You must be signed in to change notification settings - Fork 248
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
Async generator handler should follow text/event-stream
protocol
#742
Comments
text/event-stream
protocol
text/event-stream
protocoltext/event-stream
protocol
I noticed that there are already two PRs fixing it, but it's stalled for a while... |
I created an alternative framework called Spiceflow inspired by Elysia here: https://github.com/remorses/spiceflow It has support for Zod, async generators using server sent events and a lot more |
I'm unsure about how to transfer Elysia's types to this function, but here is a transformer that can be called with an async generator that transforms the Elysia response from the more general long-polling HTTP response to the more specific Server Sent Event spec: const sseEvent = (data: string) => `data: ${data}\n\n`;
export function sse(generator: any) {
return async function* (ctx: any) {
ctx.set = {
...ctx.set,
headers: {
...ctx.set.headers,
"x-accel-buffering": "no",
"content-type": "text/event-stream",
"cache-control": "no-cache",
},
};
for await (const data of generator(ctx)) {
yield sseEvent(JSON.stringify(data));
}
};
} It can be called like this: new Elysia()
.get(
"/source/:docId",
sse(async function* ({ params: { docId } }) {
while (true) {
yield { msg: "Hello world!", docId };
await delay(1000);
yield { msg: "Goodbye!" };
await delay(1000);
}
}),
) |
What version of Elysia.JS is running?
"elysia": "^1.1.3"
What platform is your computer?
Darwin 23.5.0 arm64 arm
What steps can reproduce the bug?
The output of this code will be:
There are several problems with this code:
[object Object]
Async generator yielding an object results in[object Object]
output #741elysia/src/handler.ts
Line 156 in 8173d90
What is the expected behavior?
Elysia should return a
text/event-stream
compatible output if the handler is an async generator:What do you see instead?
Elysia concatenates the outputs inline calling .toString() on each of them
Additional information
No response
The text was updated successfully, but these errors were encountered: