Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/ayonli_jsext/sse.ts>EventEndpoint

A JavaScript extension package for building strong and modern applications.
Latest
class EventEndpoint
extends EventTarget
import { EventEndpoint } from "https://deno.land/x/ayonli_jsext@v0.9.72/sse.ts";

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

// 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

// 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);

Constructors

new
EventEndpoint(request: T, options?: EventEndpointOptions)
new
EventEndpoint()
new
EventEndpoint(request: Request | IncomingMessage | Http2ServerRequest, ...args: any[])

Properties

private
[_closed]: boolean
private
[_lastEventId]: string
private
[_reconnectionTime]: number
private
[_response]: Response | null
private
[_writer]: WritableStreamDefaultWriter<Uint8Array>
readonly
closed: boolean

Indicates whether the connection has been closed.

readonly
lastEventId: string

The last event ID that the server has sent.

readonly
response: T extends Request ? Response : null

The response that will be sent to the client, only available when the instance is created with the Request API.

Methods

private
buildMessage(data: string, options?: { id?: string | undefined; event?: string | undefined; }): Uint8Array
addEventListener(
type: "close",
listener: (this: EventEndpoint<T>, ev: CloseEvent) => void,
options?: boolean | AddEventListenerOptions,
): void

Adds an event listener that will be called when the connection is closed.

addEventListener(
type: string,
options?: boolean | AddEventListenerOptions,
): void
close(noReconnect?): void

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.

dispatchEvent(event: MessageEvent<string>): boolean

Dispatches an message event that will be sent to the client.

removeEventListener(
type: "close",
listener: (this: EventEndpoint<T>, ev: CloseEvent) => void,
options?: boolean | EventListenerOptions | undefined,
): void
removeEventListener(
type: string,
options?: boolean | EventListenerOptions | undefined,
): void
send(data: string, eventId?: string | undefined): Promise<void>

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.

sendEvent(
event: string,
data: string,
eventId?: string | undefined,
): Promise<void>

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.