keep SSE connection alive

This commit is contained in:
m5r 2022-06-27 14:03:49 +02:00
parent eaf5d897ae
commit 740b59f389

View File

@ -12,21 +12,8 @@ export let loader: LoaderFunction = ({ request }) => {
new ReadableStream({
start(controller) {
const encoder = new TextEncoder();
const onNotification = (notification: NotificationPayload) => {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(notification)}\n\n`));
};
let keepAliveTimeout = setTimeout(keepAlive, 30 * 1000);
let closed = false;
function close() {
if (closed) {
return;
}
closed = true;
events.removeListener("notification", onNotification);
request.signal.removeEventListener("abort", close);
controller.close();
}
events.addListener("notification", onNotification);
request.signal.addEventListener("abort", close);
@ -34,6 +21,31 @@ export let loader: LoaderFunction = ({ request }) => {
close();
return;
}
function onNotification(notification: NotificationPayload) {
controller.enqueue(encoder.encode(`data: ${JSON.stringify(notification)}\n\n`));
}
function keepAlive() {
if (closed) {
return;
}
controller.enqueue(encoder.encode(":\n\n"));
keepAliveTimeout = setTimeout(keepAlive, 30 * 1000);
}
function close() {
if (closed) {
return;
}
closed = true;
clearTimeout(keepAliveTimeout);
events.removeListener("notification", onNotification);
request.signal.removeEventListener("abort", close);
controller.close();
}
},
}),
{