Using socket io plugin, emitting message to all rooms

Trying to build a chat feature with one to one chat and group chat.
Facing issue in emitting message, trying to send message in a room but its emitting in all the devices connected with socket

How am i suppose to handle it for group chat and one to one chat?

System Information
  • Strapi Version: 4.1.5
  • Operating System: Linux
  • Database: AWS
  • Node Version: v16.17.1
  • NPM Version: 8.19.2
  • Yarn Version: not using

STARPI BACKEND - index.js inside bootstrap

var io = require("socket.io")(strapi.server.httpServer, {

        cors: {

            origin: "http://localhost:1337",

            methods: ["GET", "POST"],

            allowedHeaders: ["my-custom-header"],

            credentials: true,

        },

    });

    io.on('connection', (socket) => {

        let header = {

            Accept: 'application/json',

            Authorization: `Bearer ${socket.handshake.auth.token}`

        }

        console.log(header);

     

        socket.on('join', ({  roomId }) => {

            console.log("roomId >> ", roomId);

            // if (roomId) {

                console.log(`room id ${roomId} connected`);

                socket.join(roomId)

            // }

            socket.on('sendMessage', async (message) => {

                try {

                    console.log(message);

                    let { msg, senderId, recieverId, senderName, } = message

                    let newCListId;

                    console.log("newCListId >> ", newCListId);

                    if (socket.roomId == roomId) io.to(socket.roomId).emit("message", message)

                }

                catch (err) {

                    console.log("err >> ", err);

                }

            })

        })

    })
2 Likes