tommyd456
tommyd456

Reputation: 10693

Refactoring Express and SocketIO app

I realise there are similar questions on SO but I can't find one that helps me. I have an Expressjs 4 app and I'm using SocketIO too. A snippet of my server.js file looks like this:

// server.js
...
var app = express();
var server = require('http').createServer(app).listen(process.env.PORT || 8080);
var io = require('socket.io')(server);

var routesApi = require('./server/routes/api');

module.exports = app;

and I have api.js:

// server/routes/api.js
...
var ctrlPosts = require('../controllers/posts');
router.post('/posts', ctrlPosts.create);
...

and my posts controller:

// controllers/posts
module.exports.create = function(req, res) {
  //how can I access io from here?
}

Question How can I access SocketIO from my posts controller?

Upvotes: 0

Views: 474

Answers (2)

erolkaya84
erolkaya84

Reputation: 1849

Create a socket.js in config directory and export io

// socket.js
var socketio = require('socket.io')

module.exports.listen = function(app){
    io = socketio.listen(app)

    posts = io.of('/posts')
    posts.on('connection', function(socket){
        socket.on ...
    })

    return io
}

and then call it in your controller

// controller
var io = require('./config/socket').listen(app)

Upvotes: 1

n32303
n32303

Reputation: 829

You can design your posts controller to accept parameter in constructor.

var controller = function(server){
    var io = require('socket.io')(server);
    var module = {
        create : function(req, res) {...}
    }
    return module;
}

Similar to this, you can design your routes api to accept server parameter and call posts controller like this:

var api = function(server){
    var ctrlPosts = require('../controllers/posts')(server);
}

and require api like this:

var routesApi = require('./server/routes/api')(server);

Upvotes: 1

Related Questions