I am trying encapsule a socket.io instance in a module. I did this but it looks a bit messy because i have to inject some dependencies for authentication of the socket transport from express / passport.
My problem is i want to access the socket instance outside of the module like socket.on("newDevice", function (data) {});
The socket instance which i get by the connection event is inside the function and it even may not exist on creation because no connection is established. This simply looks kind of wrong to me. I dont want to inject more and more depencies just because i need them inside of the function scope.
I thought about doing the sio.on('connection', function(socket) {});
outside of the module. And maybe i could do it twice, first inside of the module and then outside but i would create two listeners i guess.
Is there any good practice or pattern how to do this properly?
var io = require('socket.io');
var socket = function (server, sessionStore, cookieParser, authentication) {
var sio = io.listen(server);
// Configure socket.io
sio.configure(function () {
// Authorize the socket.io request
sio.set('authorization', function (data, accept) {
// Authorization is done here
});
});
sio.on('connection', function(socket) {
var lastActionTime = new Date();
// Get the userId from the session
var session = socket.handshake.session;
var userId = session.passport.user;
var sessionID = socket.handshake.sessionID;
var userdata = null;
// Deserialize user by the userId
authentication.deserializeUser(userId, function(err, user) {
// get the userdata
});
socket.on('disconnect', function() {
});
socket.on('brightnessChange', function(data) {
// TODO Do something here device control
// Broadcast to other devices
this.broadcast.emit('brightnessChange', data);
});
});
return sio;
};
module.exports = socket;
I would suggest, the below, flexibility and scales well. I've tried both ways and resulted in using multiple connection events.
I thought about doing the sio.on('connection', function(socket) {}); outside of the module. And maybe i could do it twice, first inside of the module and then outside but i would create two listeners i guess.