Briefly about the structure of what is. When starting the application
server.listen(port); server.on('error', onError); server.on('listening', onListening); require('socket')(server);
The line require('socket')(server)
- connects the file:
module.exports = function(server){ var io = require('socket.io')(server); io.set('origins','*:*'); //io.set('origins','localhost:*'); io.on('connection', function (socket) { log.info("Socket is connect"); }); };
Now, more to the point, in the application there are controllers that are inherited from the base:
var BaseController = require("core/base/baseController"); class AccountPageController extends BaseController{ constructor(params){ super(params); //more actions ... } methodForPage (){ //more actions ... } } module.exports = AccountPageController;
And, let's say, there is a need to send a message like this in methodForPage()
:
socket.emit('msg',{text:'server say:' + new Date()});
But, the variable socket
is available only inside io.on('connection')
. How to make it available inside the controller? Or how to define it inside the base controller so that it is available in all controllers?
And there is one more thing, for example, there is a need to set up a socket event inside the controller, for example:
methodForPage (){ //more actions ... socket.on('msg', (data) => { //do record data to db this.dbh.query(/*more actions*/); }); //more actions ... }
At the same time, we want to use the properties of this controller to, for example, write data received from a socket to the database.
Is it possible to implement all of the above in this form, and if so, what should be done for this? Is this the right approach?