export function postComment(req, res) {
const user = decodeToken(req);
let saveComment, saveJob, saveUser, activity, jobUser;
function pushToJob(comment) {
saveComment = comment;
Job.findById(req.params.id)
.then((data) => {
job = data;
data.comments.push(saveComment._id)
return data.save()
}).catch((err) => {
throw new Error(`The error at pushing to job is ${err}`)
})
}
function updateCommentWithJobId(job) {
saveComment.jobId = {
_id: job._id,
title: job.title
}
return saveComment.save()
}
function addActivityToUser(comment) {
saveComment = comment;
User.findById(user._id)
.then((data) => {
saveUser = data;
activity = {
activity: 'comment',
comment: saveComment._id,
jobAuthor: {
_id: saveJob.userId._id,
name: saveJob.userId.name
}
}
saveUser.activities.unshift(activity);
return saveUser.save()
}).catch((err) => {
throw new Error(`The error at addActivityToUser is ${err}`)
})
}
function addUserToComment(user) {
saveUser = user;
saveComment.userId = {
_id: saveUser._id,
name: saveUser.name,
profile_image: saveUser.profile_image
}
return saveComment.save()
}
function addActivityToJobUser(comment) {
saveComment = comment
User.findById(saveJob.userId)
.then((data) => {
if (saveJob.userId !== user._id) {
data.activities.unshift(activity);
}
return data.save()
}).catch((err) => {
throw new Error(`The error at addActivityToJobUser ${err}`)
})
}
function emitCommentEvent(user) {
jobUser = user
let comment = {
userId: saveJob.userId,
room: saveJob.room,
comment: saveComment
}
comEmit.emit('comment', comment);
return res.status(200).json({ message: 'Comment posted successfully' });
}
Comment.create(req.body)
.then(pushToJob)
.then(updateCommentWithJobId)
.then(addActivityToUser)
.then(addUserToComment)
.then(addActivityToJobUser)
.then(emitCommentEvent)
.catch((err) => {
res.status(500).json({ message: 'An error occurred while posting your comment, please try again' })
})
}
This is controller for one of my api, and I am emitting the comment
event every time someone posts a comment on an author's post. The problem is that the same event gets fired multiple times. The line console.log('about to emit comment')
gets triggered just once.
I tried looking for a solution, but didn't find any answer yet.
What could be the cause for such behavior?
EDIT: Here's the listener for the event.
socketio.on('connection', function(socket){
Chat.find({})
.then((data)=>{
//Some independent socket events
comEmit.on('comment', (data) => {
console.log('comment posted ', data)
if (userId === data.userId) {
socket.join(data.room);
}
socket.in(data.room).emit('commentPosted', data.comment)
})
})
})
As I can check the logs, 'comment posted'
gets logged multiple times and the data is the same.