import { EventEndpoint } from "https://deno.land/x/ayonli_jsext@v0.9.72/esm/sse.js";
An SSE (server-sent events) implementation that can be used to send messages
to the client. This implementation is based on the EventTarget
interface
and conforms the web standard.
Events:
close
- Dispatched when the connection is closed.
Examples
Example 1
Example 1
// with Web APIs
import { EventEndpoint } from "@ayonli/jsext/sse";
export default {
async fetch(req: Request) {
const events = new EventEndpoint(req);
events.addEventListener("close", (ev) => {
console.log(`The connection is closed, reason: ${ev.reason}`);
});
setTimeout(() => {
events.dispatchEvent(new MessageEvent("my-event", {
data: "Hello, World!",
lastEventId: "1",
}));
}, 1_000);
return events.response!;
}
}
Example 2
Example 2
// with Node.js APIs
import * as http from "node:http";
import { EventEndpoint } from "@ayonli/jsext/sse";
const server = http.createServer((req, res) => {
const events = new EventEndpoint(req, res);
events.addEventListener("close", (ev) => {
console.log(`The connection is closed, reason: ${ev.reason}`);
});
setTimeout(() => {
events.dispatchEvent(new MessageEvent("my-event", {
data: "Hello, World!",
lastEventId: "1",
}));
}, 1_000);
});
server.listen(3000);
Methods
Closes the connection.
By default, when the connection is closed, the client will try to
reconnect after a certain period of time, which is specified by the
reconnectionTime
option when creating the instance.
However, if the noReconnect
parameter is set, this method will mark
the client as closed based on the last event ID. When the client
reconnects, the server will send a 204 No Content
response to the
client to instruct it to terminate the connection.
It is important to note that the server depends on the last event ID to
identify the client for this purpose, so the server must send a globally
unique lastEventId
to the client when sending messages.
Sends a message to the client.
The client (EventSource
or EventConsumer) will receive the
message as a MessageEvent
, which can be listened to using the
message
event.
Sends a custom event to the client.
The client (EventSource
or EventConsumer) will receive the
event as a MessageEvent
, which can be listened to using the custom
event name.