Dominic Bou-Samra
Dominic Bou-Samra

Reputation: 15416

NodeJS and SocketIO. How to organize exposing the SocketIO instance

I have an app.js file like so:

...
var socket  = require('./app/sockets')(io)
var routes  = require('./app/routes')(server, socket)
...

The sockets.js looks like so:

exports = module.exports = function(io) {
  return {
    emit: function() {
      io.emit('hi', "Some stuff")
    }
  }
}

The routes.j file looks like so:

exports = module.exports = function(app, io) {
  ...
  var user   = require('./controllers/user')(io)
  app.get({ path: '/users/:id', version: '1.0' }, user.getUserById);
  ...
}

Finally, my user.js file looks like so:

exports = module.exports = function(io) {
  return {
    ...
    getPersonById: function(req, res, next) {
      ....
      io.emit("Hello")
      ...
    },
    ....
  }
}

Is there a better way to organize this? I feel like I am threading my io instance through 4 different files. I just want a singleton instance I can emit events on, from within my controller.

Upvotes: 1

Views: 524

Answers (1)

cieszynka
cieszynka

Reputation: 91

I,m using something like this, in express.io :

app.js

var router = require('./routes/router'),
    express = require('express.io'),
    app = new express();

app.http().io();
app.use(app.router);
app = router.index(app);
app.listen(3000);

./routes/router.js

exports.index = function(app){
var IndexIo = require(__maindir + '/routes/io/IndexIo');

app.io.route('page/action', IndexIo.action);
app.io.route('page/action2', IndexIo.action2);
return app;

};

/routes/io/IndexIo.js

exports.action = function(req){
doSomething();
req.io.emit('doSomething', {});
}

exports.action2 = function(req){
    doSomething();
    req.io.emit('doSomething', {});
}

Upvotes: 1

Related Questions