Snoopy
Snoopy

Reputation: 1357

Call socket.io API from an external file

I am trying to call my Socket.io interface from another file that is express routes. Lets say I want to create the following group chat with this and then send a notification to the involved users in the group chat,

routes.js

    router.post(
  "/save-groupchat",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    new GroupChat({
      creator: req.user._id,
      groupName: req.body.groupName,
      groupMembers: userList
    })
      .save()
      .then(newGroup => {
        GroupChat.findOne(newGroup)
          .populate("groupMembers.user")
          .then(groupChat => {
            //Notify the user's as well
            userList.map((user, key) => {
              NotificationCenter.findOneAndUpdate(
                { owner: user.user },
                {
                  $push: {
                    notifications: {
                      $each: [
                        {
                          type: "group-invite",
                          title:
                            "You have been invited to " +
                            req.body.groupName +
                            " by " +
                            req.user.name,
                          notificationTriggeredBy: req.user._id
                        }
                      ],
                      $position: 0
                    }
                  }
                }
              )
                .then(() => {
                    //How do I call the socket here <---------------------------------
                  console.log("Notified User: " + req.body.userList[key].name);
                })
                .catch(err => {
                  console.log(
                    "Error when inviting: " +
                      req.body.userList[key].name +
                      "\n " +
                      err
                  );
                });
            });

            res.json(groupChat);
          });
      });
  }
);

./microservice/chat/chat (Socket Interface)

And then my socket interface is like this,

   let user_list = {};
      io.sockets.on("connection", socket => {
        socket.on("send-notification", notification => {
          console.log("How do I get here from the other file?");
        });
    })
...

Here is how I have my server.js file

var http = require("http").Server(app);
var io = require("socket.io")(http);
ChatMicroservice = require("./microservice/chat/chat")(io);

How would I access the socket interface and use the user_list of sockets to send out the notifications?

Upvotes: 0

Views: 82

Answers (1)

ArUn
ArUn

Reputation: 1337

To call socket.io API from an external file you should either create a singleton class and export it or save socket object to a global variable, and save the connected socket id in the database corresponding to the user. so whenever a socket connection is established to the server, the socket id ie, socket.id is saved in the database corresponding to the user-id.

so your socket interface becomes

 global.io = io;
   io.sockets.on("connection", socket => {

    // add your method to save the socket id (socket.id) 
    // user-id passed can be accessed socket.handshake.query.userId


        socket.on("send-notification", notification => {
          console.log("How do I get here from the other file?");
        });
    })

In your other file call

global.io.to(id).emit(event, value);

If you are planning to scale your application horizontally use socket.io-redis in your Socket Interface

 const redis = require('socket.io-redis');
 global.io.adapter(redis({ host: redisUrl, port: redisPort }));

Upvotes: 1

Related Questions