Skip to content

Commit

Permalink
feat: implement broadcastToAuthedClients
Browse files Browse the repository at this point in the history
  • Loading branch information
solufa committed Jul 16, 2024
1 parent c48a0c6 commit 470c066
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions server/service/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ let fastify: FastifyInstance;

const users: Record<DtoId['user'], WebSocket | undefined> = {};

const sendJson = (socket: WebSocket, data: WebSocketData): void => {
if (socket.readyState !== WebSocket.OPEN) return;

socket.send(JSON.stringify(data));
};

export const websocket = {
init: (app: FastifyInstance): void => {
fastify = app;
Expand All @@ -26,13 +32,14 @@ export const websocket = {
});
},
send: (userId: DtoId['user'], data: WebSocketData): void => {
users[userId]?.send(JSON.stringify(data));
users[userId] && sendJson(users[userId], data);
},
broadcastToAuthedClients: (data: WebSocketData): void => {
Object.values(users)
.filter((user) => user !== undefined)
.forEach((socket) => sendJson(socket, data));
},
broadcast: (data: WebSocketData): void => {
fastify.websocketServer.clients.forEach((socket) => {
if (socket.readyState !== WebSocket.OPEN) return;

socket.send(JSON.stringify(data));
});
fastify.websocketServer.clients.forEach((socket) => sendJson(socket, data));
},
};

0 comments on commit 470c066

Please sign in to comment.