diff --git a/README.md b/README.md index 3b4fc44..accba61 100644 --- a/README.md +++ b/README.md @@ -51,11 +51,24 @@ es.addEventListener("error", (event) => { } }); +es.addEventListener("done", (event) => { + console.log("Done SSE connection."); +}); + es.addEventListener("close", (event) => { console.log("Close SSE connection."); }); ``` +### Done vs Close + +`done` events will fire when server closes the connection. +By default, the client will automatically reconnect when this happens. +You can disable reconnections by setting the `pollingInterval` option to `0`. +`close` events will fire when the connection is terminated by the client, using `.close()`. + +### Headers and params + If you want to use Bearer token and/or topics, look at this example (TypeScript): ```typescript diff --git a/index.d.ts b/index.d.ts index eb77c42..4820cc4 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,4 +1,4 @@ -export type BuiltInEventType = 'open' | 'message' | 'error' | 'close'; +export type BuiltInEventType = 'open' | 'message' | 'error' | 'done' | 'close'; export type EventType = E | BuiltInEventType; export interface MessageEvent { @@ -12,6 +12,10 @@ export interface OpenEvent { type: 'open'; } +export interface DoneEvent { + type: 'done'; +} + export interface CloseEvent { type: 'close'; } @@ -55,6 +59,7 @@ export interface EventSourceOptions { type BuiltInEventMap = { 'message': MessageEvent, 'open': OpenEvent, + 'done': DoneEvent, 'close': CloseEvent, 'error': ErrorEvent | TimeoutEvent | ExceptionEvent, }; diff --git a/src/EventSource.js b/src/EventSource.js index 6a7b146..1dc8f26 100644 --- a/src/EventSource.js +++ b/src/EventSource.js @@ -24,6 +24,7 @@ class EventSource { open: [], message: [], error: [], + done: [], close: [], }; @@ -117,6 +118,7 @@ class EventSource { if (xhr.readyState === XMLHttpRequest.DONE) { this._logDebug('[EventSource][onreadystatechange][DONE] Operation done.'); this._pollAgain(this.interval, false); + this.dispatch('done', { type: 'done' }); } } else if (xhr.status !== 0) { this.status = this.ERROR;