First cut
This commit is contained in:
24
ws/broadcast.js
Normal file
24
ws/broadcast.js
Normal file
@@ -0,0 +1,24 @@
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user