Aller au contenu

SSE Streams

Ce contenu n’est pas encore disponible dans votre langue.

SSE routes open a persistent HTTP connection and push a sequence of named events to the client on a configurable interval. No extra dependencies — yRest uses Node.js native streams and Fastify’s raw reply API.

When a stream depends on state — a chat, a job queue, notifications triggered by other requests — replace _events with _handler and let a function drive the stream:

_routes:
- _method: SSE
_path: /events/chat
_sse:
_handler: chatStream
yrest.handlers.ts
import { defineSseHandler } from "@yrest/cli";
export const chatStream = defineSseHandler((req, raw, { collection }) => {
for (const message of collection("messages").findAll()) {
raw.write(`event: message\ndata: ${JSON.stringify(message)}\n\n`);
}
raw.end();
});

The handler receives (req, raw, ctx): the request, the Node.js ServerResponse and the same ctx.collection() access as handler functions. yRest sends the SSE headers and the keep-alive comments; the handler writes frames and calls raw.end() when it is done. _interval, _loop, _repeat and _events are not used.

A handler missing from the handlers file answers 501 before the stream opens. One that throws sends an event: error frame and the stream is closed. See SSE handler streams for a full chat example.