This commit is contained in:
seb
2026-09-23 15:15:45 +02:00
parent a46e9742f4
commit 68aadd483b
3 changed files with 35 additions and 26 deletions

View File

@@ -8,15 +8,16 @@
/** @type {Set<SseClient>} */
const clients = new Set();
const KEEP_ALIVE_MS = 25_000;
const KEEP_ALIVE_MS = 20_000;
/**
* Register an open SSE response. Caller must write the initial headers.
* @param {import('express').Response} res
* @param {{ companyId: number, userId: number }} meta
* @param {import('express').Request} [req]
* @returns {() => void} unsubscribe
*/
export function subscribe(res, { companyId, userId }) {
export function subscribe(res, { companyId, userId }, req) {
/** @type {SseClient} */
const client = {
res,
@@ -24,7 +25,7 @@ export function subscribe(res, { companyId, userId }) {
userId,
keepAlive: setInterval(() => {
if (res.writableEnded) return;
res.write(': keepalive\n\n');
res.write(': heartbeat\n\n');
}, KEEP_ALIVE_MS),
};
clients.add(client);
@@ -35,6 +36,7 @@ export function subscribe(res, { companyId, userId }) {
};
res.on('close', unsubscribe);
req?.on('close', unsubscribe);
return unsubscribe;
}