30. Realtime chat in the group using socket IO

Now we need to make a realtime chat effect. When you send a message in a group, it should automatically be displayed to all the members of that group. But only if they have opened the group page. Otherwise, they will simply see a notification. Like we did for our private chat tutorial. First, open your “api/server.js” file and make the users array global inside the socket IO connection.

socketIO.on("connection", function (socket) {

    socket.on("connected", function (email) {
        global.users[email] = socket.id;
    });
});

Also, you need to assign the socketIO object to the group’s module.

groups.socketIO = socketIO;

Then open your api/modules/groups.js and create this socketIO object.

module.exports = {
    
    socketIO: null,

    ...
};

After that, we need to create a self variable that will be accessible inside all routes.

// initialize the module
init: function (app, express) {

    // create a new router object from express
    const router = express.Router();

    const self = this;

    ...
};

Now, in the “/sendMessage” POST route, we need to send the socket event to all the members and admin of the group.

const messageObject = {
    _id: document.insertedId,
    message: message,
    sender: object.sender,
    receiver: object.receiver,
    attachment: object.attachment,
    type: "group",
    isRead: false,
    createdAt: createdAt
};

// send socket events to all members
for (let a = 0; a < group.members.length; a++) {
    if (group.members[a].user._id.toString() != user._id.toString()) {
        if (typeof global.users[group.members[a].user.email] !== "undefined") {
            self.socketIO.to(global.users[group.members[a].user.email]).emit("sendMessage", {
                title: "New message has been received.",
                data: messageObject
            });
        }
    }
}

// send socket event to admin
if (group.createdBy._id.toString() != user._id.toString()) {
    self.socketIO.to(global.users[group.createdBy.email]).emit("sendMessage", {
        title: "New message has been received.",
        data: messageObject
    });
}

And finally in your AppHeader.vue, when the socket “sendMessage” event is attached. We will append the incoming message in your groupMessages array.

socketIO.on("sendMessage", async function (data) {
    if (self.$route.path == "/chat/" + data.data.sender.email) {
        store.commit("appendMessage", data.data)
    }

    if (self.$route.path == "/groups/detail/" + data.data.receiver._id.toString()) {
        store.commit("appendGroupMessage", data.data)
    }

    ...
});

It will display the message in the group chat without having to refresh the page.

group realtime chat
group realtime chat

So that’s it, your group chat is now realtime. You can learn more about sockets from here.





Please disable your adblocker or whitelist this site!