Skip to content

Commit

Permalink
Implement conversation handling in sendMessage controller
Browse files Browse the repository at this point in the history
  • Loading branch information
rebeljelly2147 committed Jan 19, 2025
1 parent 7aff1fb commit 4aac61c
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
31 changes: 28 additions & 3 deletions backend/controllers/message.controller.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,36 @@
import Conversation from "../models/conversation.model.js"; // .js is mandatory for proper working of ES6 modules

export const sendMessage = async (req, res) => {
// res.send('Send Message Route');
// console.log('Message sent by userId', req.params.id);
try {
const {id: recieverId} = req.params;
const {message} = req.body;
const senderId = req.user._id;
console.log('Message sent by userId', senderId);
const {id: recieverId} = req.params;
const senderId = req.user._id; // because we used protectRoute middleware in the route
// console.log('Message sent by userId', senderId);

let conversation = await Conversation.findOne({
participants: {$all: [senderId, recieverId]} // participants array contains senderId and recieverId $all is used to check if both are present
}); // this will find the conversation between sender and reciever

if(!conversation) {
conversation = await Conversation.create({
participants: [senderId, recieverId]
});
}; // this will create a new conversation if it does not exist

const newMessage = {
sender : senderId,
reciever : recieverId,
message
}// this will create a new message

if(newMessage){
conversation.messages.push(newMessage._id);
}// this will push the new message to the conversation messages array

res.status(201).json({newMessage, conversation});

} catch (error) {
console.log("Error in sendMessages controller : ",error.message);
res.status(500).json({message: "Internal Server Error During Sending Message"});
Expand Down
3 changes: 2 additions & 1 deletion backend/routes/message.routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import protectRoute from "../middleware/protectRoute.js";

const router = express.Router();

router.post("/send/:id", protectRoute,sendMessage);
router.post("/send/:id", protectRoute,sendMessage);
// protectRoute is a middleware to protect the route so that we can use req.user._id in the controller

export default router;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"scripts": {
"server": "nodemon backend/server.js"
},
"type": "module",
"type": "module",
"keywords": [],
"author": "",
"license": "ISC",
Expand Down

0 comments on commit 4aac61c

Please sign in to comment.