Node.js - Socket.io - What's the best way to organize sockets?

I have never used socket.io, I am wondering how I should build it inside my models, at the moment I am planning to have a Socket class and another model that would be used for use in the UserModel for example.

Then, in UserModel.authenticate (), I would call the socket to add the user to some room I guess.

I'm just wondering if this will go the way, or if I should respect some kind of design pattern, or if my design is wrong. (no reverse experience with the nest, so you better ask people who have it!)

Let me know if you know a better approach or some example, I think it is simple, but I could be wrong.

+3


source to share


1 answer


What are you trying to implement, such as a facade schema while trying to abstract away socket mechanics.

In my opinion this implementation can be very tricky since you have to do a very good abstraction for sockets, I have a completely different approach, how I do it, to split up the sockets by grouping them into aggregates and the responsibility, say I have a socket file that will only have user interaction for managing streams of activity (in the case of a social network) or managing products, etc. are looking at them as you were looking at controllers in the MVC pattern.

to split sockets into different physical files, you can manage event handlers with files like this:

io.of('namespace').on('connection',function(socket){
    var eventHandlers = {
        'user': new userLib.UserSocket(socket, app),
        'document': new documentLib.documentSocket(socket,app)
    };
    for (var category in eventHandlers) {
        var handler = eventHandlers[category].handlers;
        for (var event in handler) {
        socket.on(event, handler[event]);
        }
    }
    socket.on('error',function(err){
        console.error(err);
    });
    socket.on('disconnect',function(){
         console.log('disconnect');
    });

}

      



in your custom event handler file (ex user.socket.js):

var signup = function(){
    var self = this; 
    //TODO: do your code
};

var authenticate = function(){
var self = this; 
    //TODO: do your code
}

exports.UserSocket = function(socket,app){
    this.app = app;
    this.socket = socket;

    this.handlers = {
        authenticate:authenticate.bind(this),
        signup: signup.bind(this)
    };
};

      

Hope it helps!

+3


source







All Articles