I'm running into a problem implementing Socket.io on my Node.js server. I have two files, one with the middleware and one that starts the server and initializes the socket.
The problem I'm running into is accessing the socket in the middleware. I've attached my code, and the actual middleware functions are in the user export, and the userSocket export is simply used to create the socket in the server file.
I'd like to be able to do something like io.emit("message", message) inside the sendMessage method of the user middleware, but I that method can't access the io variable, and if it could, I'm not sure if that would work since the server creates the socket based off the userSocket function. Is there any way I can handle socket events in specific middleware?
// this is the middleware file
const userSocket = (io) => {
io.on("connection", (socket) => {
socket.on("join-room", (id) => {
socket.join(id);
console.log(`user joined room ${id}`);
});
});
};
module.exports.userSocket = userSocket;
module.exports.user = {
sendMessage: // access the socket here
}
// this is the server file
const express = require("express");
const app = express();
const { createServer } = require("http");
const httpServer = createServer(app);
const port = 3000;
const io = require("socket.io")(httpServer, { cors: { origin: "*" } });
const { userSocket } = require("./resources/users/user");
userSocket(io);
httpServer.listen(port);
console.log(`Listening on port ${port}`);