Skip to content

Commit

Permalink
Merge pull request #45 from jennydo/chat-ui
Browse files Browse the repository at this point in the history
Chats: Populate userId when get chats & Update chat controllers & New socket event
  • Loading branch information
jennydo authored Jun 23, 2024
2 parents 97d4bbb + f5ebc74 commit 67778d9
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 20 deletions.
10 changes: 10 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ cron.schedule("0 */15 * * *", () => {
// generatePrompt()
// })

const onlineUsers = new Set();

// connect to MongoDB
const MONGO_URI = process.env.MONGO_URI;
Expand All @@ -99,9 +100,17 @@ mongoose
socket.on("setup", (userData) => {
socket.join(userData._id);
socket.emit("connected");
onlineUsers.add(userData._id);
socket.emit('onlineUsers', Array.from(onlineUsers));
console.log(userData.username + " joined Room: " + userData._id);
});

socket.on('userConnected', (userId) => {
onlineUsers.add(userId);
// socket.emit('updateUserStatus', { userId, status: 'online' });
io.emit('updateUserStatus', { userId, status: 'online' });
});

socket.on("join chat", (room) => {
socket.join(room);
console.log("User Joined Room: " + room);
Expand All @@ -124,6 +133,7 @@ mongoose

socket.off("setup", () => {
console.log("USER DISCONNECTED");
io.emit('updateUserStatus', { userId, status: 'offline' });
socket.leave(userData._id);
});
});
Expand Down
46 changes: 28 additions & 18 deletions controllers/chats-controller.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const asyncHandler = require("express-async-handler");
const Chat = require("../models/chats-model");
const User = require("../models/users-model");

const Message = require("../models/messages-model");

// Create a chat Or Access to One Chat
// assyncHandler helps with async ops and error handling, avoiding repetitive try catch
Expand All @@ -21,14 +21,14 @@ const accessChat = asyncHandler(async (req, res) => {
{ users: { $elemMatch: { $eq: userId } } }, // userId in req body
],
})
.populate("users", "username avatar")
.populate("users", "username avatar pronounce location interests bio")
.populate("latestMessage");


// populate chat sender
isChat = await User.populate(isChat, {
path: "latestMessage.sender",
select: "username avatar",
select: "username avatar pronounce location interests bio",
});


Expand All @@ -39,7 +39,7 @@ const accessChat = asyncHandler(async (req, res) => {
} else {
// Create a new chat
var chatData = {
chatName: "sender",
chatName: req.user.username,
isGroupChat: false,
users: [req.user._id, userId],
};
Expand All @@ -49,7 +49,7 @@ const accessChat = asyncHandler(async (req, res) => {
// sends the created chat to users
const FullChat = await Chat.findOne({ _id: createdChat._id }).populate(
"users",
"username avatar"
"username avatar pronounce location interests bio"
);
res.status(200).json(FullChat);
} catch (error) {
Expand All @@ -63,14 +63,13 @@ const accessChat = asyncHandler(async (req, res) => {
const fetchChats = asyncHandler(async (req, res) => {
try {
Chat.find({ users: { $elemMatch: { $eq: req.user._id } } })
.populate("users", "username avatar")
.populate("groupAdmin", "username avatar")
.populate("users", "username avatar pronounce location interests bio")
.populate("latestMessage")
.sort({ updatedAt: -1 })
.then(async (results) => {
results = await User.populate(results, {
path: "latestMessage.sender",
select: "username avatar",
select: "username avatar pronounce location interests bio",
});
res.status(200).send(results);
});
Expand All @@ -80,7 +79,23 @@ const fetchChats = asyncHandler(async (req, res) => {
}
});


const deleteChat = async (req, res) => {
const { chatId } = req.params;
console.log('chatId to delete', chatId);
if (!chatId) {
return res.status(400).json({ error: "Chat ID is required." });
}
try {
// await Message.deleteMany({ chatId: id });
const chat = await Chat.findOneAndDelete({ _id: chatId });
if (!chat) {
return res.status(404).json({ error: "Chat not found." });
}
res.status(200).json({ message: "Chat deleted successfully.", chat });
} catch (error) {
return res.status(500).json({ error: "An error occurred while trying to delete the chat." });
}
};

//--------------------------------------GROUP CHAT------------------------------------------------
// Create New Group Chat
Expand Down Expand Up @@ -124,15 +139,9 @@ const renameGroup = asyncHandler(async (req, res) => {

const updatedChat = await Chat.findByIdAndUpdate(
chatId,
{
chatName: chatName,
},
{
new: true,
}
)
.populate("users", "-password")
.populate("groupAdmin", "-password");
{ chatName },
{ new: true } // Ensure that the updated document is returned
).populate("users", "-password");

if (!updatedChat) {
res.status(404);
Expand Down Expand Up @@ -199,6 +208,7 @@ const addToGroup = asyncHandler(async (req, res) => {
module.exports = {
accessChat,
fetchChats,
deleteChat,
createGroupChat,
renameGroup,
addToGroup,
Expand Down
5 changes: 3 additions & 2 deletions routes/chats-routes.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
const express = require('express')
const { accessChat, fetchChats, createGroupChat, renameGroup, removeFromGroup, addToGroup } = require('../controllers/chats-controller');
const { accessChat, fetchChats, deleteChat, createGroupChat, renameGroup, removeFromGroup, addToGroup } = require('../controllers/chats-controller');
const requireAuth = require('../middleware/requireAuth');

const chatsRouter = express.Router();
chatsRouter.use(requireAuth);

chatsRouter.post("/", accessChat);
chatsRouter.get("/", fetchChats);
chatsRouter.delete("/:chatId", deleteChat);
chatsRouter.post("/group", createGroupChat);
chatsRouter.put("/rename", renameGroup);
chatsRouter.patch("/rename", renameGroup);
chatsRouter.put("/groupremove", removeFromGroup);
chatsRouter.put("/groupadd", addToGroup);

Expand Down

0 comments on commit 67778d9

Please sign in to comment.