Socket.IO on controller

可紊 提交于 2020-01-24 20:47:07

问题


I'm pretty new to sockets and I've been struggling to implement some of the documentation i've seen online. This is my set up currently and I wanted to run socket.io against just the healthcheck api endpoint (/api/v1/healthcheck) how would I go about running socket io in the healthcheck controller? and emit changes to the response? Any help is appreciated, i'm tearing my hair out :(

Server.js

const socket = require('socket.io')

const healthcheck = require('./routes/healthcheck');
const auth = require('./routes/auth');
const users = require('./routes/users');

const server = app.listen(
  PORT,
  console.log(
    `Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.cyan.bold
  )
);

let io = require('socket.io')(server);
app.set("io", io);

//Auth
app.use('/api/v1/auth', auth);
app.use('/api/v1/users', users);  
//Health check
app.use('/api/v1/healthcheck', healthcheck);

/routes/healthcheck.js

const express = require('express');
const { checkHealth } = require('../controllers/healthcheck');

const router = express.Router();

router.post('/', checkHealth);

module.exports = router;

/controllers/healthcheck.js

const asyncHandler = require('../middleware/async');

exports.checkHealth = asyncHandler(async (req, res, next) => {
    res.status(200).json({
        success: true,
        data: {
            status: "Alive!"
        }
    });
});

回答1:


You can pass in the instance of io into that healthcheck route and then simply listen to events and take action. Sample code below.

server.js

const socket = require('socket.io')

const server = app.listen(
  PORT,
  console.log(
    `Server running in ${process.env.NODE_ENV} mode on port ${PORT}`.cyan.bold
  )
);

let io = require('socket.io')(server);
app.set("io", io);

// pass in io to the relevant route
const healthcheck = require('./routes/healthcheck')(io);
const auth = require('./routes/auth');
const users = require('./routes/users');

//Auth
app.use('/api/v1/auth', auth);
app.use('/api/v1/users', users);  
//Health check
app.use('/api/v1/healthcheck', healthcheck);

healthcheck route

const express = require('express');
const { checkHealth } = require('../controllers/healthcheck');

const router = express.Router();

module.exports = (io) => {
   router.post('/', checkHealth);

   io.on('connection', socket => {
      socket.emit('hello', {message: 'helloworld'});

      socket.on('reply', checkHealth.someMethod); 
   });

   return router;
}

I would rather create endpoints in files - same as you do for express routes, and init these in your server.js as follows:

let io = require('socket.io')(server);
app.set("io", io);

io.on('connection', socket => {
   require('./myendpointexample')(socket);
});

myendpointexample.js

module.exports = (socket) => {
   socket.on('myevent', (message) => {
      mycontroller.myFunction(message).then(result => {
          socket.emit('myEvent', result);
      });
   });
};


来源:https://stackoverflow.com/questions/58864595/socket-io-on-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!