Home > Blockchain >  How to use socket.io inside controller of nodejs?
How to use socket.io inside controller of nodejs?

Time:11-01

I am finding answers for How to use socket emit,broadcast functions inside nodejs controller functions?. I am initializing my io.on("connection") inside index.js file.

I am adding my file structure can anyone help me how to pass my socket or how to use my socket instance inside my controller.

enter image description here

Suppose I have this express route :

router.post("/current-uzone-user/update-bio", verifyToken, updateUserBio);

In my function:

export const updateUserBio = async (req, res) => {
  try {
    const { bio } = req.body;
    if (!bio) return res.status(400).send("Bio is required");
    const user = await UUser.findById(req.user._id).exec();
    if (!user) return res.status(400).send("User not found");
    if (user._id != req.user._id)
      return res.status(400).send("You are not authorized to delete this todo");
    user.bio = bio;
    await user.save();
    return res.status(200).send("User bio updated successfully");
  } catch (err) {
    //console.log(err);
    await sendSlackMessage({
      text: `Server error at ${new Date(
        Date.now()
      ).toLocaleString()} => ${JSON.stringify(err, null, 4)}`,
    });
    return res.status(400).send("Something went wrong");
  }
};

Suppose I want to emit one socket message after update bio success or fail.

Can some one help me how to do it here. Thank you ❤️

CodePudding user response:

You can access the socket and emit events from anywhere using the below code.

//app.js or index.js
const app = express();
var http = require("http");
var server=http.createServer(app).listen(2525, (req, res) => {
  console.log("Server running on", 2525);
});
var socketIO = require("socket.io");
var io = socketIO(server);
global.io = io //Importent line

//Add the below statement to your controller code
global.io.emit("eventname", "yourdata"); //Importent line
  • Related