import { EventConsumer } from "https://deno.land/x/ayonli_jsext@v0.9.72/sse.ts";
Unlike the EventSource API, which takes a URL and only supports GET
request, the EventConsumer API accepts a Response
object and reads
the messages from its body, the response can be generated from any type of
request, usually returned from the fetch
function.
This API doesn't support active closure and reconnection, however, we can
use AbortController
in the request to terminate the connection, and add
a event listener to the close event and reestablish the connection manually.
Events:
error
- Dispatched when an error occurs, such as network failure. After this event is dispatched, the connection will be closed and theclose
event will be dispatched.close
- Dispatched when the connection is closed. If the connection is closed due to some error, theerror
event will be dispatched before this event, and the close event will have thewasClean
set tofalse
, and thereason
property contains the error message, if any.message
- Dispatched when a message with the default event type is received.- custom events - Dispatched when a message with a custom event type is received.
NOTE: This API depends on the Fetch API and Web Streams API, in Node.js, it requires Node.js v18.0 or above.
Examples
Example 1
Example 1
import { EventConsumer } from "@ayonli/jsext/sse";
const response = await fetch("http://localhost:3000", {
method: "POST",
headers: {
"Accept": "text/event-stream",
},
});
const events = new EventConsumer(response);
events.addEventListener("close", (ev) => {
console.log(`The connection is closed, reason: ${ev.reason}`);
if (!ev.wasClean) {
// perhaps to reestablish the connection
}
});
events.addEventListener("my-event", (ev) => {
console.log(`Received message from the server: ${ev.data}`);
});
Constructors
Properties
The time in milliseconds that instructs the client to wait before reconnecting.
NOTE: The EventConsumer API does not support auto-reconnection, this value is only used when we want to reestablish the connection manually.
Methods
Adds an event listener that will be called when the connection is
interrupted. After this event is dispatched, the connection will be
closed and the close
event will be dispatched.
Adds an event listener that will be called when the connection is closed.
If the connection is closed due to some error, the error
event will be
dispatched before this event, and the close event will have the wasClean
set to false
, and the reason
property contains the error message, if
any.
Adds an event listener that will be called when a message with the default event type is received.
Adds an event listener that will be called when a message with a custom event type is received.