This commit is contained in:
seb
2026-10-28 19:31:41 +01:00
parent 01d6aa0e3f
commit 1881830b0a
13 changed files with 81 additions and 27 deletions

View File

@@ -45,36 +45,41 @@ export function subscribe(res, { companyId = null, userId, clientId }, req) {
/**
* Updates the active company scope for all open SSE streams of a user
* (e.g. when the user selects or switches company on a pre-company stream)
* and emits a `company` event to those streams.
* and emits `user` and `company` events to those streams.
* @param {number} userId
* @param {number|null} companyId
*/
export function setUserCompany(userId, companyId) {
if (userId == null) return;
const nextCompanyId = companyId ?? null;
const frame = `event: company\ndata: ${JSON.stringify({ companyId: nextCompanyId })}\n\n`;
const userFrame = `event: user\ndata: ${JSON.stringify({ selectedCompanyId: nextCompanyId })}\n\n`;
const companyFrame = `event: company\ndata: ${JSON.stringify({ companyId: nextCompanyId })}\n\n`;
for (const client of clients) {
if (client.userId !== userId) continue;
client.companyId = nextCompanyId;
if (!client.res.writableEnded) {
client.res.write(frame);
client.res.write(userFrame);
client.res.write(companyFrame);
}
}
}
/**
* Clears a deleted company from any open SSE streams bound to it
* and emits a `company` event (`{ companyId: null }`) to those streams.
* and emits `user` (`{ selectedCompanyId: null }`) and `company` (`{ companyId: null }`)
* events to those streams.
* @param {number} companyId
*/
export function clearDeletedCompany(companyId) {
if (companyId == null) return;
const frame = `event: company\ndata: ${JSON.stringify({ companyId: null })}\n\n`;
const userFrame = `event: user\ndata: ${JSON.stringify({ selectedCompanyId: null })}\n\n`;
const companyFrame = `event: company\ndata: ${JSON.stringify({ companyId: null })}\n\n`;
for (const client of clients) {
if (client.companyId !== companyId) continue;
client.companyId = null;
if (!client.res.writableEnded) {
client.res.write(frame);
client.res.write(userFrame);
client.res.write(companyFrame);
}
}
}