How can I access my websocket inside of a different function?

Viewed 24

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}`);
1 Answers

This is what I had done for a project I was working on:

index.js (main file)
After you do the initial config with the http server export your socket: 

io.sockets.on("connection", function (socket) {
console.log("New Client Connected");
});

httpServer.listen(3300, () => {
  console.log(`App listening on port ${3300}`);
});
//export
const socketIoObject = io;
export default socketIoObject;

And then in your middleware you can use it as follows:

//middleware file

//import
import socketIoObject from "../index.js"

//your route
idk.get("/something",(req,res,next)=>{

//your logic if any
//using the socket

  socketIoObject.emit('student', {
        //emit the data to the socket
    });
}

Hope this helps

Related