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