Skip to content

Commit

Permalink
Fixed message/user endpoint bugs and added clarifying comments
Browse files Browse the repository at this point in the history
  • Loading branch information
Keagan Aromin authored and Keagan Aromin committed Jan 11, 2025
1 parent 6ca7ea3 commit 0ac9d50
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 11 deletions.
19 changes: 13 additions & 6 deletions backend/controllers/message.controller.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,34 @@
import Conversation from "../models/conversation.model.js";
import Message from "../models/message.model.js";
import { getReceiverSocketId, io } from "../socket/socket.js";
//import { getReceiverSocketId, io } from "../socket/socket.js";

export const sendMessage = async (req, res) => {
try {
//req attributes: message, *receiverId, user
const { message } = req.body;
const { id: receiverId } = req.params;
const senderId = req.user._id;
const { id: receiverId } = req.params; //assign id at the end of url /send/:id" to receiverId
const senderId = req.user._id; //protectRoute.js adds user to req attributes, and ._id is a special field for mognoose models

//find the specific conversation between the sender and receiver (no groupchats)
let conversation = await Conversation.findOne({
participants: { $all: [senderId, receiverId] },
});

//if this convo doesn't exist, open up a new DM
if (!conversation) {
conversation = await Conversation.create({
participants: [senderId, receiverId],
});
}

//initialize a new message
const newMessage = new Message({
senderId,
receiverId,
message,
});

//if new message is successfully created, add the _id to the messages attribute of conversation object
if (newMessage) {
conversation.messages.push(newMessage._id);
}
Expand All @@ -33,7 +38,8 @@ export const sendMessage = async (req, res) => {
// await conversation.save();
// await newMessage.save();

// this will run in parallel
// saves the message to db, access by going to MongoDB website > cluster > chat-app-db > conversations/messages
// the Promise.all() allows us to run conversation.save() and newMessage.save() in parallel
await Promise.all([conversation.save(), newMessage.save()]);

res.status(201).json(newMessage);
Expand All @@ -45,9 +51,10 @@ export const sendMessage = async (req, res) => {

export const getMessages = async (req, res) => {
try {
const {id:userToChatId} = req.params.id; //get req.params.id and rename to userToChatId
const senderId = req.user._id;
const {id:userToChatId} = req.params; //get req.params.id and rename to userToChatId
const senderId = req.user._id; //get user._id again using protectRoute.js

console.log(senderId)
//conversation document, has array of mesage references as an attribute, use mongoose populate method to get actual contents of each message
const conversation = await Conversation.findOne({
participants: {$all: [senderId, userToChatId]},
Expand Down
3 changes: 2 additions & 1 deletion backend/middleware/protectRoute.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import User from "../models/user.model.js";

const protectRoute = async (req, res, next) => {
try {
//req params: cookies (has jwt), user (assigned at end)
const token = req.cookies.jwt;
//case where there is no token in the request
if (!token) {
Expand All @@ -29,7 +30,7 @@ const protectRoute = async (req, res, next) => {
//because of this line of code, we can use req.user._id instead of req.user.Id
req.user = user;

//this says that once everything has run, exit this function and call the next one
//this says that if everything has successfully ran by this point, exit this function and call the "next" function (passed as a parameter)
next();
} catch (error) {
console.log("Error in protectRoute middleware: ", error.message);
Expand Down
6 changes: 4 additions & 2 deletions backend/routes/message.routes.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import express, { Router } from "express";
import { sendMessage } from "../controllers/message.controller";
import protectRoute from "../middleware/protectRoute";
import { getMessages, sendMessage } from "../controllers/message.controller.js";
import protectRoute from "../middleware/protectRoute.js";

const router = express.Router();

//when we have a post request, we first run protectRoute until the next() call is reached, then we run sendMessage
//protectRoute makes sure that only authenticated users can send a message
//access id using req.params.id
router.get("/:id", protectRoute, getMessages)
router.post("/send/:id", protectRoute, sendMessage)

export default router;
4 changes: 2 additions & 2 deletions backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import dotenv from "dotenv";
import cookieParser from "cookie-parser";

import authRoutes from "./routes/auth.routes.js";
import messageRoutes from "./routes/auth.routes.js";
import userRoutes from "./routes/auth.routes.js";
import messageRoutes from "./routes/message.routes.js";
import userRoutes from "./routes/user.routes.js";

import connectToMongoDB from "./db/connectToMongoDB.js";

Expand Down

0 comments on commit 0ac9d50

Please sign in to comment.