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
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");
};