Skip to content

Commit

Permalink
fix: the delete message apiEndpoint-chatapp as per review
Browse files Browse the repository at this point in the history
  • Loading branch information
arnb-smnta committed Mar 22, 2024
1 parent ff7b625 commit 8e14268
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 75 deletions.
85 changes: 23 additions & 62 deletions src/controllers/apps/chat-app/message.controllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ const sendMessage = asyncHandler(async (req, res) => {
const deleteMessage = asyncHandler(async (req, res) => {
//controller to delete chat messages and attachments

const { chatId, messageId, attachmentId } = req.params;
const { chatId, messageId } = req.params;

//Find the chat based on chatId

Expand Down Expand Up @@ -190,78 +190,39 @@ const deleteMessage = asyncHandler(async (req, res) => {
);
}

//Checking if 15 mins has passed since the message sent or not

const currentTime = new Date();
const messageCreatedAt = message.createdAt;
const timeDifferenceMinutes = (currentTime - messageCreatedAt) / (1000 * 60); //calculating the time difference in minutes

if (timeDifferenceMinutes > 15) {
if (
!chat.participants.some(
(user) => user?.toString() === req.user?._id.toString()
)
) {
throw new ApiError(
400,
"15 mins have passed you cannot delete this message"
);
}

// If frontend sends the attachment id and message has more than one attachment
//Then delete only the attachment sent by the user otherwise delete the whole message
if (attachmentId && message.attachments.length > 1) {
const attachmentIndex = message.attachments.findIndex(
(attachment) => attachment._id.toString() === attachmentId
401,
"You are not part of this group you cannot delete this message"
);

if (attachmentIndex === -1) {
throw new ApiError(404, "Attachment not found");
}

const deletedAttachment = message.attachments.splice(attachmentIndex, 1);
removeLocalFile(deletedAttachment[0].localPath);

await message.save({ validateBeforeSave: false });
// logic to emit socket event about the message attachment deleted to the other participants
chat.participants.forEach((participantObjectId) => {
// here the chat is the raw instance of the chat in which participants is the array of object ids of users
// avoid emitting event to the user who is deleting the message
if (participantObjectId.toString() === req.user._id.toString()) return;

// emit the delete message attachment event to the other participants frontend with messageId as the payload
emitSocketEvent(
req,
participantObjectId.toString(),
ChatEventEnum.MESSAGE_DELETED_EVENT,
message._id
);
});

return res
.status(200)
.json(new ApiResponse(200, {}, "Message attachment deleted succesfully"));
}
//If the message is attachment remove the attachments from the server
if (message.attachments.length > 0) {
//If the message is attachment remove the attachments from the server
message.attachments.map((asset) => {
removeLocalFile(asset.localPath);
});
}
//deleting the message from DB
try {
await ChatMessage.deleteOne({
_id: new mongoose.Types.ObjectId(messageId),
});
} catch (error) {
throw new ApiError(500, "Internal Server Error");
}
await ChatMessage.deleteOne({
_id: new mongoose.Types.ObjectId(messageId),
});

//Updating the last message of the chat to the previous message after deletion
const lastMessage = await ChatMessage.findOne(
{ chat: chatId },
{},
{ sort: { createdAt: -1 } }
);
//Updating the last message of the chat to the previous message after deletion if the message deleted was last message
if (chat.lastMessage.toString() === message._id.toString()) {
const lastMessage = await ChatMessage.findOne(
{ chat: chatId },
{},
{ sort: { createdAt: -1 } }
);

await Chat.findByIdAndUpdate(chatId, {
lastMessage: lastMessage ? lastMessage?._id : null,
});
await Chat.findByIdAndUpdate(chatId, {
lastMessage: lastMessage ? lastMessage?._id : null,
});
}
// logic to emit socket event about the message deleted to the other participants
chat.participants.forEach((participantObjectId) => {
// here the chat is the raw instance of the chat in which participants is the array of object ids of users
Expand Down
22 changes: 9 additions & 13 deletions src/routes/apps/chat-app/message.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,15 @@ router
sendMessage
);

//attachment id is optional for multiple attachments in a single message
//Delete message route based on Message id

router.route("/:chatId/:messageId/:attachmentId?").delete(
mongoIdPathVariableValidator("chatId"),
mongoIdPathVariableValidator("messageId"),
(req, res, next) => {
if (!req.params.attachmentId) {
return next();
}
mongoIdPathVariableValidator("attachmentId")[0](req, res, next);
},
validate,
deleteMessage
);
router
.route("/:chatId/:messageId")
.delete(
mongoIdPathVariableValidator("chatId"),
mongoIdPathVariableValidator("messageId"),
validate,
deleteMessage
);

export default router;

0 comments on commit 8e14268

Please sign in to comment.