-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessageController.js
More file actions
171 lines (147 loc) · 4.37 KB
/
messageController.js
File metadata and controls
171 lines (147 loc) · 4.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// import Message from "../models/message.js";
import User from "../models/User.js";
import Message from "../models/Message.js";
import cloudinary from "../lib/cloudinary.js";
import {io, userSocketMap} from "../server.js"
// get all users except the logged in user
// export const getUsersForSideBar = async (req, res) => {
// try {
// const userId = req.user._id;
// const filteredUsers = await User.find({ _id: { $ne: userId } }).select(
// "-password"
// );
// // count number of unread messages
// const unseenMessages = {};
// const promises = filteredUsers.map(async (user) => {
// const messages = await Message.find({
// senderId: user._id,
// receiverId: userId,
// });
// if (messages.length > 0) {
// unseenMessages[user._id] = messages.length;
// }
// });
// await Promise.all(promises);
// res.status(200).json({
// success: true,
// users: filteredUsers,
// unseenMessages,
// });
// } catch (error) {
// console.log(error.message);
// res.status(500).json({ success: false, message: error.message });
// }
// };
export const getUsersForSideBar = async (req, res) => {
try {
const userId = req.user?._id;
if (!userId) {
return res
.status(401)
.json({ success: false, message: "Unauthorized" });
}
const filteredUsers = await User.find({ _id: { $ne: userId } }).select(
"-password"
);
const unseenMessages = {};
const promises = filteredUsers.map(async (user) => {
const count = await Message.countDocuments({
senderId: user._id,
receiverId: userId,
seen: false, // 🔍 Only unread messages
});
if (count > 0) {
unseenMessages[user._id] = count;
}
});
await Promise.all(promises);
res.status(200).json({
success: true,
users: filteredUsers,
unseenMessages,
});
} catch (error) {
console.log(error.message);
res.status(500).json({ success: false, message: error.message });
}
};
// get all messages for the selected user
// export const getMessages = async (req, res) => {
// try {
// const { id: selectedUserId } = req.params;
// const myId = req.user._id;
// const messages = await Message.find({
// $or: [
// { senderId: myId, receiverId: selectedUserId },
// { senderid: selectedUserId, receiverId: myId },
// ],
// });
// await Message.updateMany(
// { senderId: selectedUserId, receiverId: myId },
// { seen: true }
// );
// res.status(200).json({ success: true, messages });
// } catch (error) {
// console.log(error.message);
// res.status(500).json({ success: false, message: error.message });
// }
// };
export const getMessages = async (req, res) => {
try {
const { id: selectedUserId } = req.params;
const myId = req.user._id;
const messages = await Message.find({
$or: [
{ senderId: myId, receiverId: selectedUserId },
{ senderId: selectedUserId, receiverId: myId },
],
}).sort({ createdAt: 1 }); // oldest to newest
// mark all messages from selected user to me as seen
await Message.updateMany(
{ senderId: selectedUserId, receiverId: myId, seen: false },
{ $set: { seen: true } }
);
res.status(200).json({ success: true, messages });
} catch (error) {
console.log(error.message);
res.status(500).json({ success: false, message: error.message });
}
};
//mark message as seen using id
export const markMessageAsSeen = async (req, res) => {
try {
const { id } = req.params;
await Message.findByIdAndUpdate(id, { seen: true });
res.status(200).json({success: true})
} catch (error) {
console.log(error.message);
res.status(500).json({ success: false, message: error.message });
}
};
export const sendMessage = async (req, res) => {
try {
const { text, image } = req.body;
const receiverId = req.params.id;
const senderId = req.user._id;
let imageUrl;
if (image) {
const uploadResponse = await cloudinary.uploader.upload(image);
imageUrl = uploadResponse.secure_url; // ✅ fixed typo
}
const newMessage = await Message.create({
senderId,
receiverId,
text,
image: imageUrl,
});
// emit the new message to the receiver's socket
const receiverSocketId = userSocketMap[receiverId];
if (receiverSocketId) {
io.to(receiverSocketId).emit("newMessage", newMessage);
}
res.status(201).json({ success: true, newMessage });
} catch (error) {
console.log(error.message);
res.status(500).json({ success: false, message: error.message });
}
};