Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

138
Vistas
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 Respuestas
Responde la pregunta

0

Maybe, you import socket in controller file incorrect

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda