Search code examples
node.jssocketssocket.ioexpress-4

Node JS & Socket.io Advice - Is it better to post information to a database through a route, or through the socket?


I am currently building a new application which, at a basic level, lets users add a task which needs to be completed, and then lets a different group of users pick up the task and complete it.

Previously, I took over building a real-time chat application written with NodeJS and Socket.io and on that, all the messages were posted to a database over the socket connection.

In the current application I am doing the same, but was thinking if it might be better off to post the information to the database via the route instead, then emitting the socket event on success to update the list of available tasks.

I was just looking for advice, how would you guys do this? Commit info to the database through a route or over the socket?


Solution

  • If you go the route way things are pretty much laid out for you to be sure whether or not your update worked or not. Socket doesn't guarantee neither success nor failure, by default.

    But you could program to make it. For e.g.

    client: send data

    socket.emit('update', data); // send data
    

    server: receive data & send back an update as to whether the operation was successful or not

    socket.on('update', function(data){
        findOrUpdateOrWhateverAsync(function(err){
            if(!err) socket.emit('update', null); // send back a "null" on success
            else socket.emit('update', err.message); // or send back error message
        });
    });
    

    client: receive update on error/success

    socket.on('update', function(err){
        if(err) alert(err);
    });