I'm working on a Node.js chat app project using the ws library. I have it up and running but I'm still making improvements and adding stuff like authentication, etc. Before I get too far, I am wondering what the best functional approach to handling messages (and other events) is. For example, right now I have the following code to handle a message from the client (I cut out most of it, just keeping in one function to use as an example):
wss.on('connection', (ws, req) => {
// Give them the funtions (uses local ws)
function handleMessage(msgJSON) {
let incMsg = {};
try {
incMsg = JSON.parse(msgJSON); // message from client
} catch {
console.error("Could not parse sent JSON");
return;
}
switch (incMsg.type) {
case "message":
ws.send("Message sent.");
// send the message to other clients:
wss.clients.forEach(client => {
// send message to all open clients but not this client
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`${client.username}: ${incMsg.message}`);
}
}
// some more cases, like for "meta"
}
}
// more functions ...
ws.on('message', message => {
handleMessage(message);
});
}
This strategy takes advantage of having the ws variable inside the inner function, but this makes the wss.on('connection') handler full of a lot of functions. Is it better practice to use this approach or to make a global sort of function that you then pass the client into? My alternate idea looks like this:
function handleMessage(msgJSON, ws) { // accepts the current client
let incMsg = {};
try {
incMsg = JSON.parse(msgJSON); // message from client
} catch {
console.error("Could not parse sent JSON");
return;
}
switch (incMsg.type) {
case "message":
ws.send("Message sent.");
// send the message to other clients:
wss.clients.forEach(client => {
// send message to all open clients but not this client
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`${client.username}: ${incMsg.message}`);
}
}
break;
// some more cases, like for "meta" ...
}
}
// more functions ...
wss.on('connection', (ws, req) => {
ws.on('message', message => {
handleMessage(message, ws); // pass along the ws client
});
}
```
// some more cases, like for "meta", and would have referred you to the partial paragraph: "Excerpts of large projects are fine, but if you have omitted too much, then reviewers are left imagining how your program works.". The user that supplied an answer didn't have much context about the other code yet to be implemented or even a broad view of what the websocket application did other than showing messages. If you have more questions then please ask on meta. \$\endgroup\$