So here is the situation, I need to create a room for two people that exist in our database. The problem is that I can't identify with those users based on their sockets.
Let's say there are two random users user1 and user2. Now, user1 wants to initiate chat with user2, so I need to create a room when the user1 initiates and join the two users to that room. Here's the problem that sockets join a room, and socket.id changes with reconnection from the same host. So, I can't figure out how do I join user2 to the room.
Here's the code.
export default function(socketio) {
let sockets = [];
let people = {};
const findUserById = function findUserById(data) {
for (let x in people) {
if (people[x].userId === data) {
return x;
}
}
}
/**
* [createRoom Creates a room for two users]
* @param {[type]} data1 [Mongoose objectId for user]
* @param {[type]} data2 [Mongoose objectId for user]
* @return {[type]} [A string of 6 characters that identifies with the room]
*/
const createRoom = function createRoom(data1, data2) {
const user1 = data1.toString().slice(-3);
const user2 = data2.toString().slice(-3);
return user1 + user2;
}
socketio.on('connection', function(socket) {
console.log(`Connection made from ${socket.id}`);
sockets.push({
socket: socket,
id: socket.id
});
socketio.on('join', (data) => {
people[socket.id] = {
userId: data
}
})
socketio.on('initiate', (data) => {
const receiverSocket = findUserById(data.receiver);
if (receiverSocket) {
let room = createRoom(people[socket.id].userId, receiverSocket.userId)
let chat = new Chat({
room: room
});
/*
Now, we'll add the chats to the respective users.
*/
User.findById(people[socket.id].userId, (err, foundUser) => {
foundUser.chats.push({
room: room,
partner: receiverSocket.userId
})
foundUser.save((err, success) => {
if (!err || success) {
User.findById(receiverSocket.userId, (err, secondUser) => {
secondUser.chats.push({
room: room,
partner: people[socket.id].userId
})
secondUser.save()
})
}
})
})
let user1Socket = sockets.filter((el) => {
return el.id === socket.id
})
let user2Socket = sockets.filter((el) => {
return el.id === receiverSocket
})
user1Socket.socket.join(room);
user2Socket.socket.join(room);
socketio.sockets.in(room).emit('private room created', {
room: room
});
}
})
socketio.on('job', (data) => {
socketio.broadcast.emit('jobPosted', data);
})
socketio.on('message', (data) => {
Chat.findOne({room: data.room})
.then((data)=>{
data.chat.push({'content': data.message, 'userId': data.sender, 'date': new Date()})
data.save()
.then((success)=>{
socketio.sockets.in(data.room).emit('messageReceived', data.message)
})
})
})
});
}
The logic here was that each time a connection is made I would store that socket.id and later on pull it out to create a room. But this fails when socket.id changes.
Can anyone help me with this?