Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
node.js send notification to specific user in controller

index.js file


var users = [];

let addUser = (userId, socketId) => {
  !users.some((user) => user.userId === userId) &&
    users.push({ userId, socketId });
};

let removeUser = (socketId) => {
  users = users.filter((item) => item.socketId !== socketId);
};

const getUser = (userId) => {
  console.log("inside function", users);
  return users.find((item) => item.userId === userId);
};

io.on("connection", (socket) => {
  socket.on("addUser", async (userId) => {
    await addUser(userId, socket.id);
    io.emit("getUsers", users);
    console.log(users) // print array of users like this 
      // [{userId:'userId',socketId: 'socket id'}]
  });

  socket.on("disconnect", () => {
    removeUser(socket.id);
    io.emit("getUsers", users);
  });
});

const socketIoObject = io;
const usersInObject = users;
module.exports.ioObject = { socketIoObject, usersInObject };

controller file

exports.createNotifications = async (req, res) => {
  try {
    const { userId, title, type = "default", isPublic } = req.body;

    if (!title) {
      return res.status(401).send("Data is required");
    }

    const notification = await notificationsModel.create({
      userId,
      title,
      type,
      isPublic: userId ? false : true,
    });
    console.log("socket", socket.ioObject.usersInObject); // return empty 
    // array [] !!!!
    return res.status(200).send("sent");
  } catch (err) {
    return res.status(400).send(err.message);
  }
};

why I can't get the users list in the controller, I got an empty array !!

I need to share the users list in all files to can get the user by function getUser to get the socketId of a specific user to can send a notification to him

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Maybe, you import socket in controller file incorrect

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!