Search code examples
node.jssocketswebsocketsocket.iochat

What is the best way to store messages in db and emit them with socket.io?


I have a chat app, something like Whatsapp. I'm considering two ways to store messages in db and also emit them. My approach now is that client emits new message, server is listening then store that message in database and return whole message back to server. Server after that emits new message to all clients in session/group. So bascially it server first stores messages in db and then emits them back to clients.

this is my code on server:

//this is just basic example on how it works for now
io.on("connection", socket => {
    socket.on("message", async (message) =>{
        db.query("call insertnewMessage(params)",(res)=>{
            if(res[0]){
                socket.emit("newMessage",{newMessage: res[0]});
            }
        })
    }
}

Second approach is to first with normal http request send message to REST api (not socket server), rest api query database to insert message, returns new message to server and server returns whole new message to client and then client emits new message to socket server? In this approach socket server does not need to query db and I actually know that message is sent ( it is inserted in db).

I read from somewhere that every new connection is actually new instance of socket on server. Wouldn't it made that if I have code from my example, and if every connection is new instance, that if I send new message to server and have for example 5 clients, it would be inserted 5 times in db because every socket connection will query db if they are independent? Am i missing something here and can someone make this clearer please.


Solution

  • I'm doing this now, and my thinking is, on the client you get your user and what Rooms he is in. Then still on client you make ws to listen to only these rooms.

    So then on the server if the table you changing is matching the room number, broadcast to only to who is listening for that room number.

    With supabase this was easy todo because they have RealTime DB setup, but I'm learning doing this with server and ws so i have more control and maybe more resource at my disposal