0

This is post-event Route . when a user Posts an event then that event should be sent to all its follower! I have maintained the Follower Array for that.

How to that using Socket.io ????

 module.exports.postEvent = (req,res) => {
       Events.saveEvent(req.body , (err,saveEvent)=>{
          var response = {
              status : 500,
              message : err
          };
          var id = req.userId;
          if(err){
              res.status(response.status)
                  .json(response.message);
          }else {
              // find the data of user from token and
                user.getuserbyname(id ,(err,user)=>{
                    if(err){
                        res.status(response.status)
                            .json(response.message);
                    }else{

                        // send to all user subscribers via socket.io
                        async.each(user.followers ,(id , callback)=>{

                         what will be the code here???


                        })
                    }
              })
          }
      })
    };
kartik
  • 69
  • 8
  • I would suggest providing a bit more code, like where you're implementing your socket library in your back end. Are you using express? – Andrew Senner Oct 24 '17 at 21:27
  • yeah, i am using express. here in my ASYNC.each loop I am iterating an array of followers and I want to send a new post to every subscriber or follower, so what do I need to write in that for loop? – kartik Oct 25 '17 at 05:38

1 Answers1

0

Attach the io instance to your app when you setup the io server.

app.io = io;

It's then available via the request object

router.post('/event', function(req, res){
  req.app.io.emit('message', data)
})

Default Room

Each socket connection has a "Default Room" identified by its Socket#id.

You can send to that room in you request handler with:

req.app.io.to(socket_id).emit('my message', msg)

Or via the socket in a socket io handler:

socket.broadcast.to(socket_id).emit('my message', msg)

Rooms

SocketIO also provides a concept of Rooms. Instead of managing subscription arrays your self, you can make sockets join and leave a room and then emit to that room.

io.on('connection', function(socket){
  socket.join(`room:${user}`)
})

io.to(`room:${user}`).emit('my message', msg)
Matt
  • 68,711
  • 7
  • 155
  • 158