I am working on socket for chatting. Here is my socket code in nodejs file which is working well.
The outer socket io.emit
working good and emits the message to all the users which are connected to that conversationId
.
But the socket.broadcast.emit
(when user uses the app) which I am using to notify user, emits(socket.broadcast.emit
) events multiple times. Why this is happening? Am I completely missing the socket approach.
socket.on('sendMessage', async(action2) => {
try {
action2.author = socket.decoded.id
action2.readBy = [socket.decoded.id]
action2.deliveredTo = [socket.decoded.id]
const createMessage = await Message.create(action2)
const sender = await User.findOne({ _id: socket.decoded.id }, { firstName: 1 })
const memebers = //some api call to get members
const promises = members.map(async(member) => {
// socket for message
const socketNotification = {
// my object
}
console.log(socketNotification, 'socketNotifcication')
socket.broadcast.emit(`messageSocket${member.memberId}`, socketNotification)
})
await Promise.all(promises)
io.emit(action2.conversationId, messages) // "newMessage"
} catch (err) {
throw err
}
})
from Socket emitting event multiple times
No comments:
Post a Comment