A Server-Sent Event (SSE) client using Generators.
This package is distributed via npm:
npm install sse-gen
To instantiate a client, call new
on the class, and pass it a url
value.
const client = new SSEClient<T>("/events");
An optional options
object can be passed as a second argument.
type SSEClientOptions = {
onStatusUpdate?: StatusUpdateHandler;
reconnect?: { maxAttempts: number; delay: number };
};
The use of those options is explained further down this document.
To connect to the server (based on the URL passed to the constructor), call the connect
method on the instantiated client.
client.connect();
To close the connect to the server, call the close
method on the instantiated client.
client.close();
To add an handled for messages sent by the server, pass an EventHandlerMessage
function to the on
method.
client.on((event) => {
console.log(event.data);
});
Note that if you are receiving a JSON string, you might need to parse it using JSON.parse()
.
The main motivation of using a Generator to handle events in this SSE client is the possibility to have asynchronous message handlers. Using a Generator ensures that messages will be processed one by one, and that new messages will wait for the previous messages to be processed.
If passed a reconnect
option to the constructor, the client will try to reconnect automatically.
The number of times the client will try to reconnect is defined by the maxAttempts
property of the reconnect
option. The delay between each reconnection attempt is defined by the delay
property of the reconnect
option.
const client = new SSEClient("/events", {
reconnect: {
maxAttempts: 3,
delay: 1000,
},
});
To add further custom error handling, pass an EventHandlerError
function to the catch
method.
client.catch((event) => {
console.error(event);
});
Note that the client calls close
when receiving an error.
To retrieve the URL the client is connected to, use the url
getter on the instantiated client.
const client = new SSEClient<T>("/events");
client.url; // "/events"
The client can be in different statuses:
enum SSEClientStatus {
CONNECTING = "CONNECTING",
OPEN = "OPEN",
CLOSED = "CLOSED",
}
To retrieve the status of the client, use the status
getter on the instantiated client.
const client = new SSEClient<T>("/events");
client.connect();
client.status; // "CONNECTING"
// ...
client.status; // "OPEN"
// ...
client.close();
client.status; // "CLOSED"
You can also pass a custom handler for status updates in the constructor.
const client = new SSEClient("/events", {
onStatusUpdate: (status) => {
console.log(status);
},
});