I have a MERN stack application, and I have an array that keeps track of the logged in users.
server/index.js
var connectedUsers = []
io.on('connection', (socket) => {
socket.on('addUser', (userId) => {
connectedUsers.push({userId, socket.id})
})
})
I also have a POST request for creating a Post document.
server/controllers/post
export const createPost = async (req, res) => {
const post = req.body;
const newPostMessage = new PostMessage({ ...post,
creator: req.userId, createdAt: new Date().toISOString() })
try {
await newPostMessage.save();
res.status(200).json(newPostMessage);
awardBadges(req.userId)
} catch (error) {
res.status(50).json({ message: error.message });
}
}
After creating a post document and sending it as a JSON, it will check to see if the user meets any requirements for a badge (similar to Stackoverflow badge)
export const awardBadges = async (userId) => {
// Assign awards
// Update user's awards field with the badges he received
// and mailbox field with that specifies which awards he received
}
If the user is connected and received a badge, it will emit a message so that the user will send a GET request to the database to get his mailbox field.
I know I can accomplish this by doing the following:
io.to(socket.id).emit("getMailbox");
But how can I access the socketId if it's in a different node.js file? Would I have to make the connectedUsers a global var?