Socket.io emits from Express controllers

I am new to Node.js / Express and I use it as a backend for an AngularJS application. I looked at StackOverflow for some help on my problem, but I cannot figure out how to port sentences to my code.

My application works as follows:

  • The lengthy Scala process periodically sends my Node.js. application log messages He does this by sending to the HTTP API
  • When a message is received, my application writes a log message to MongoDB
  • Log messages are then sent in real time to the Angular client.

I have a problem with Node modules, since I cannot figure out how to access the socket instance in the Express controller.

As you can see, socket.io is created there in server.js. However, I would like the controller itself, logs.js, to be able to emit a socket.io instance.

How can I access io in the controller? I'm not sure how to pass the io instance to the controller so that I can send messages?

Here is the Node code:

server.js

var app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server); require('./lib/config/express')(app); require('./lib/routes')(app); server.listen(config.port, config.ip, function() { console.log('Express server listening on %s:%d, in %s mode', config.ip, config.port, app.get('env')); }); io.set('log level', 1); // reduce logging io.sockets.on('connection', function(socket) { console.log('socket connected'); socket.emit('message', { message: 'You are connected to the backend through the socket!' }); }); exports = module.exports = app; 

routes.js

 var logs = require('./controllers/logs'), middleware = require('./middleware'); module.exports = function(app) { app.route('/logs') .post(logs.create); } 

logs.js

 exports.create = function(req, res) { // write body of api request to mongodb (this is fine) // emit log message to angular with socket.io (how do i refer to the io instance in server.js) }; 
+6
source share
1 answer

You can use a template based on standard JS closures. The main export to logs.js will not be the controller function itself, but the factory function, which will take all the necessary dependencies and create the controller:

 exports.create = function(socket) { return function(req, res) { // write body of api request to mongodb socket.emit(); } } 

Then when you want to use it:

 app.route('/logs').post(logs.create(socket)); 

Since you configure your routes in a separate package, you must use the same template in routes.js - routes in order to get a socket to use as a parameter.

This pattern works well if you want to handle these things with DI later or test your controllers with sockets.

+7
source

Source: https://habr.com/ru/post/969516/


All Articles