1
Fork 0

Send ConnectedUsersMessages when user requests desiredName change

This commit is contained in:
Tobias Berger 2022-01-27 16:22:15 +01:00
parent 2bd036ffef
commit 82bdd733ad

View file

@ -11,6 +11,7 @@ import type {
TypingMessage,
ConnectedUser,
ConnectedUsersMessage,
DesiredNameMessage,
} from "./lib/ServerMessage";
import {
@ -97,43 +98,78 @@ async function handleCloseConnection(id: string) {
desiredNames.delete(id);
}
for (const to of webSocketServer.clients) {
to.send(
JSON.stringify({
type: MessageType.CONNECTED_USERS,
__ctx: `${id} left`,
date: Date.now(),
connected:
const connected =
Array.from(activeConnections,
(id) => {
return {
id,
desiredName: desiredNames.get(id),
} as ConnectedUser;
}),
});
for (const to of webSocketServer.clients) {
to.send(
JSON.stringify({
type: MessageType.CONNECTED_USERS,
__ctx: `${id} left`,
date: Date.now(),
connected,
} as ConnectedUsersMessage)
);
}
}
function handleNewConnection(id: string) {
activeConnections.add(id);
const connected =
Array.from(activeConnections,
(id) => {
return {
id,
desiredName: desiredNames.get(id),
} as ConnectedUser;
});
for (const to of webSocketServer.clients) {
to.send(
JSON.stringify({
type: MessageType.CONNECTED_USERS,
__ctx: `${id} joined`,
date: Date.now(),
connected:
connected,
} as ConnectedUsersMessage)
);
}
}
async function handleDesiredNameMessage(message: DesiredNameMessage, from: string) {
if (!activeConnections.has(from) && desiredNames.has(from)) {
desiredNames.delete(from);
return;
}
console.debug(`${from} set desiredName to ${message.desiredName}`);
if (message.desiredName === undefined) {
desiredNames.delete(from);
} else {
desiredNames.set(from, message.desiredName);
}
const connected =
Array.from(activeConnections,
(id) => {
return {
id,
desiredName: desiredNames.get(id),
} as ConnectedUser;
}),
});
for (const to of webSocketServer.clients) {
to.send(
JSON.stringify({
type: MessageType.CONNECTED_USERS,
__ctx: `${from} changed desiredName to ${message.desiredName}`,
date: Date.now(),
connected,
} as ConnectedUsersMessage)
);
}
@ -171,9 +207,10 @@ webSocketServer.on("connection", function connection(socket) {
} else if (isTypingMessage(message)) {
handleTypingMessage(message, authorId);
} else if (isDesiredNameMessage(message)) {
desiredNames.set(authorId, message.desiredName);
handleDesiredNameMessage(message, authorId);
}
});
socket.on("close", function close() {
console.log("closed a connection");
});