Use socket.io in controllers

后端 未结 3 1143
离开以前
离开以前 2021-01-30 00:37

I only need socket.io to emit messages to clients, if a new object is inserted to database. So my idea was to emit the message directly fr

3条回答
  •  面向向阳花
    2021-01-30 01:06

    You can solve this problem declaring io instance as global variable.
    
    at the last line of my app.js: IoInstance = require("./socket.io")(server);
    
    at the './socket.io' :
    const chatNamespace = require("./namespaces/chat");
    const notificationsNamespace = require("./namespaces/notifications");
    const auth = require("./middlewares/auth");
    
    module.exports = (server) => {
      const io = require("socket.io").listen(server);
    
      io.of("/chats")
        .use(auth)
        .on("connect", (socket) => chatNamespace({ io, socket }));
    
      io.of("/notifications")
        .use(auth)
        .on("connect", (socket) => notificationsNamespace({ io, socket }));
    
      return io;
    };
    
    then, you can use the IoInstance wherever you want, event into your controller. Btw, I could have use it into my namespaces as well, but I've just realized it right now.
    
    example of implementation in the testController.js:
    
    module.exports = async (req, res) => {
      IoInstance.of("/notifications")
        .to("myUserId")
        .emit("sendNotification", ["test", "test1"]);
      return res.send("oioi");
    };
    

提交回复
热议问题