Search code examples
node.jsexpressgethttp2

Use setInverval to perform GET requests to nodejs?


I'm using nodejs with express to read a collection in mongodb for a set of messages to display to the user. I've read about http2, but I don't know if there are any significant advantages over using setInterval on the client side to receive an updated message list. I'm basically doing:

setInterval(()=>{ 
            this.props.getSession(session_id);
        }, 5000);

This takes the _id of the mongodb document and sends it in a GET request to nodejs every 5 seconds. Is this going to cause serious problems in the wild. I'm basically terrified that this will cause horrible performance issues at scale, but I'm wondering what alternatives I have besides what looks like an incredible complicated http2 implementation that could have many security vulnerabilities.

I guess I could also rephrase my question as, will this cause my server to crash with a small number of users running this code on a certain page?


Solution

  • Ok, so I've figured out the best way to deal with this, and it is not helpful to focus too much on how the messages exist in the database. I ended up using a web-socket library called socket.io. I was able to create unique "rooms" for each group that connects to the server when the page loads. The mongodb _id for the message session is used to dynamically create a room as follows:

    io.on('connection', async function(socket){
        socket.on('session' async (session)=>{
            socket.join(session.session_id); //not shown: session join authentication
        });
        socket.on('send', async (d)=>{
    
    
            try{
                const {text} = d.body;
                const {token, session} = d.head;
                //custom function that is async to parse jwt token and do db.MessageSession.create({})
                const result = await socketMeassageAuthAndSend(session, token, text);
                const {flag, user, _id, date} = result;
    
                if(flag === 'auth'){
                   socket.broadcast.to(session).emit('socket_message_broadcast', {text,user,_id,date})
                 }else{
                   socket.emit("unauthorized", {message: "will place ip address here to send to admin panel"});
                 }}catch(err){
                     console.log(err);
                   }
         });
    

    This works to perform updates that are authenticated and authorized with a mongo database. There is no need for event driving from mongoose and it keeps the database synchronized with the user's view in real time.