I’m trying to make a simple web socket for my application, but I have problems with the find method.
const io = require('socket.io')(3002, { cors: { origin: 'http://localhost:3000' } })
const api = require('axios').create({ baseURL: 'http://localhost:3001/api', timeout: '5000' })
let users = []
async function verify(user, usePassword){
let verified
await api.get(`/users/get?username=${user.username}`)
.then(() => verified = true)
.catch(() => verified = false)
if(usePassword){
await api.post('/users/login', { data: { username: user.username, password: user.password } })
.then(() => verified = true)
.catch(() => verified = false)
}
}
io.on('connection', (socket) => {
socket.on('statusOnline', async (user) => {
if(!user || !user.username || !user.password) return io.to(socket.id).emit('error', 'Invalid user object')
const isVerified = verify(user, true)
if(!isVerified) return io.to(socket.id).emit('error', 'Problem with verifying you')
users.push({ username: user.username, password: user.password, socketId: socket.id })
console.log(users)
})
socket.on('messageSend', async (user, conversationId) => {
if(!user || !user.username || !user.password) return io.to(socket.id).emit('error', 'Invalid user object')
if(!conversationId) return io.to(socket.id).emit('error', 'No conversation id provided')
if(conversationId.length < 12) return io.to(socket.id).emit('error', 'ConversationId must be longer then 12 characters.')
const isVerified = verify(user, true)
if(!isVerified) return io.to(socket.id).emit('error', 'Problem with verifying you')
const conversation = await api.get(`/conversations/get?conversationId=${conversationId}`)
if(!conversation?.data?.members?.find((m) => m == user.username)) return socket.to(socket.id).emit('error', 'You are not in that conversation.')
const recieverUsername = conversation.data.members.find((m) => m.username != user.username)
const reciever = users.find((u) => u.username == recieverUsername)
if(!reciever) return
io.to(reciever.socketId).emit('messageRecieve', conversation.data._id)
})
socket.on('disconnect', () => {
const user = users.find((u) => u.socketId == socket.id)
console.log('Someone disconnected')
users = users.filter((u) => u.socketId != socket.id)
})
})
As you can see I have a messageSend event. The purpose of that event is to notify the reciever that he got new message.
The problem is:
Lets say that the User1 wanna send message to the User2. The User1 opens the app and sends the message. It works fine.
When the User2 wanna reply, it doesen’t.
I tryed logging the users, recieverUsername and reciever variables and discovered that the reciever is always the User1. When User2 sends the first message, reciever is always User2.
If someone know what is going on here, please help me.