Module ringo/jsgi/eventsource
This module provides the constructor for EventSource response objects, which allow pushing messages to connected clients.
Functions
- isEventSourceRequest (request)
EventSource (request)
EventSource (or Server-Sent-Events) is a server push technology utilizing plain HTTP responses. The event stream format defines three types of messages:
- data-only
- named events with data
- comments
One method for each message type is available. Data is expected to be in JSON format. EventSource instances are thread-safe.
The EventSource wraps an AsyncResponse and is used similarly:
Example
const eventSource = new EventSource(request);
// send headers and start heartbeat
eventSource.start({
"X-Additional-Header": "Foo"
});
setInterval(function() {
eventSource.event('foo-field', 'foo-value');
}, 5 * 1000);
// close the response. No more data can be written
// and the hearbeat stops.
eventSource.close();
// Each EventSource instance exposes the wrapped JSGI asynchronous response
eventSource.response
Parameters
JSGIRequest | request |
EventSource.prototype. comment (comment)
Send a comment.
Parameters
String | comment | The comment |
Throws
EventSource.prototype. event (name, data)
Send a named event
Parameters
String | name | The event name |
String | data | The event data |
Throws
EventSource.prototype. response
EventSource.prototype. start (headers, heartBeatInterval)
Start the async response. Optionally set additional headers here.
Parameters
Object | headers | Additional headers (optional) |
Number | heartBeatInterval | in seconds (optional. default: 15) |
isEventSourceRequest (request)
Static helper to check whether request accepts eventstream.
Parameters
JSGIRequest | request |
Returns
Boolean | whether the accept header matches 'text/event-stream |