25 lines
713 B
JavaScript
25 lines
713 B
JavaScript
// Central registry of all active WebSocket connections.
|
|
// Fastify-websocket exposes individual socket objects; we collect them here
|
|
// so any part of the server can broadcast without importing fastify itself.
|
|
|
|
/** @type {Set<import('ws').WebSocket>} */
|
|
const clients = new Set();
|
|
|
|
export function registerClient(socket) {
|
|
clients.add(socket);
|
|
socket.on('close', () => clients.delete(socket));
|
|
}
|
|
|
|
/**
|
|
* Broadcast a job update to every connected client.
|
|
* @param {object} payload Plain object — will be JSON-serialised.
|
|
*/
|
|
export function broadcast(payload) {
|
|
const msg = JSON.stringify(payload);
|
|
for (const ws of clients) {
|
|
if (ws.readyState === 1 /* OPEN */) {
|
|
ws.send(msg);
|
|
}
|
|
}
|
|
}
|