0

I have made a very casual commenting system, and now I want to add replies. So, when someone posts a reply on someone else's comment, that user must be notified that someone replied to their comment. In order to do that, when the replier clicks the reply button an AJAX post request is made to the server, the server then needs to get the id of the first commenter and send them a response text using socket.io (socket.io is not required to be used if there is another way to send the reply text with another module or express itself). This is my code so far:

app.post('/reply', function(req, res){
  var commenterId = req.body.userId; // this is the id of the original commenter, not the replier
  User.findOne({'_id':commenterId}, function(err, user){
    user.send({'replied': req.user._id}); // this is what I need to do, and
  //I don't know if this specific code works and that's why I'm asking if there is a way to do it with socket.io,
  // io.to(socketId).emit('reply', 'some reply text here...'); // but if I do this I don't know how to get the socketId!
  //Is there even a way to do this? Maybe with another module,
  //or some express function I don't know about? And if it is done with express how would
  //the client side code, look like? Thank you!
  });
  res.end();
});
7
  • Oh and one more thing, how can I bind a socket.io user id with an express user id? Maybe with like a JSON object but how do I use the one get the other one? Commented May 21, 2016 at 21:44
  • you need a look up table, an object with keys of the commenterId and values of the socket.io connection. you make/update this when you create the reply-able data. Commented May 21, 2016 at 22:07
  • Ok, but how do I save the express user id and socket.io user id in one JSON object. I need to "attach" the express user id to the socket.io user id, but I don't know how to get it (the socket.io user id) using express. And in reverse, I don't know how to get the express user id using the socket.io user id. Can I do this somehow? Commented May 21, 2016 at 22:12
  • you don't need an id in socket.io, or express really, unless that's what commenterId is. you need to put the object value as the actual socket.io client connection, via which you can simply send() an update notification. if this is long-term (multi reloads), then you'll need some sort of sign-in ID to key the socket.io connection by instead of the (likely) transient express one. the end result should be code usable something like activeUsers[commenterId].send({some:"thing"}) Commented May 21, 2016 at 22:22
  • The commenterId is the express id of the commenter. I thought that using that, I can send him, somehow, a message using express. Is there any function that allows me to send a message to him (the commenter), when the replier POSTs his reply? Commented May 21, 2016 at 22:29

1 Answer 1

1
//app.js file   
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var routes = require('./routes/routes')(io);
app.use('/', routes);

//router file
var express = require('express');
var router = express.Router();
var _socket = null;

//list of socket users.once they logout delete the socket by 
//delete users[_socket.userid];
var users = {};

var returnRouter = function(io) {

    io.sockets.on('connection', function (socket) {
        //now _Socket is available inside routes
       _socket =  socket;
    });

    router.post('/login', function(req, res) {
        //authentication logic
        User.findOne({'email': req.body.email}, function (err, user) {

           //userid must be unique
           _socket.userId= user.userId
           //set session variable to store id of the user
           req.session.userId = user.userId;
           //now every user has a socket associated with their id
           users[_socket.userId] = _socket;
        });
    });

    router.post('/reply', function (req, res) {
       var commenterId = req.body.userId;
       User.findOne({'_id': commenterId}, function (err, user) {

       // you can get the id of the logged in user that is the creator
       //of the original post from req.session.userId
       //if you have implemented session store

       //the commenter user object is obtained from findOne method
       users[req.session.userId].emit('notification', {
         notification: user.username+' commented on your post'
       }});
       });
       res.end();
    });

    return router;
};
module.exports = returnRouter;
Sign up to request clarification or add additional context in comments.

2 Comments

But doesn't the socket id change when the user navigates to another page within my website?
read the code completely users[_socket.userId] = _socket; stores the socket.so that it persists even on refiresh.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.