2022-02-10 21:42:53 +00:00
|
|
|
"use strict";
|
|
|
|
|
2022-02-21 03:10:49 +00:00
|
|
|
import log from '../../../io/NamespacedLog.mjs'; const l = log("sse");
|
|
|
|
|
2022-02-10 21:42:53 +00:00
|
|
|
class ServerSentEventStream {
|
|
|
|
constructor(response) {
|
|
|
|
this.response = response;
|
|
|
|
this.next_id = 0;
|
|
|
|
|
|
|
|
this.response.writeHead(200, {
|
|
|
|
"content-type": "text/event-stream",
|
|
|
|
"cache-control": "no-store"
|
|
|
|
});
|
|
|
|
this.response.flushHeaders();
|
|
|
|
}
|
|
|
|
|
|
|
|
write(event_name, data) {
|
2022-02-21 03:10:49 +00:00
|
|
|
// l.log(`event #${this.next_id} ${event_name}: ${data}`);
|
2022-02-10 21:42:53 +00:00
|
|
|
this.response.write(`id: ${this.next_id++}\n`);
|
|
|
|
this.response.write(`event: ${event_name}\n`);
|
|
|
|
this.response.write(`data: ${data}\n\n`);
|
|
|
|
}
|
|
|
|
|
|
|
|
write_json(event_name, data_obj) {
|
|
|
|
return this.write(event_name, JSON.stringify(data_obj));
|
|
|
|
}
|
2022-02-12 16:27:50 +00:00
|
|
|
|
|
|
|
end() {
|
|
|
|
this.response.end();
|
|
|
|
}
|
2022-02-10 21:42:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export default ServerSentEventStream;
|