-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessageController.js
39 lines (34 loc) · 944 Bytes
/
messageController.js
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
const Messages = require("../models/messageModel");
module.exports.getMessages = async (req, res, next) => {
try {
const { from, to } = req.body;
const messages = await Messages.find({
users: {
$all: [from, to],
},
}).sort({ updatedAt: 1 });
const projectedMessages = messages.map((msg) => {
return {
fromSelf: msg.sender.toString() === from,
message: msg.message.text,
};
});
res.json(projectedMessages);
} catch (ex) {
next(ex);
}
};
module.exports.addMessage = async (req, res, next) => {
try {
const { from, to, message } = req.body;
const data = await Messages.create({
message: { text: message },
users: [from, to],
sender: from,
});
if (data) return res.json({ msg: "Message added successfully." });
else return res.json({ msg: "Failed to add message to the database" });
} catch (ex) {
next(ex);
}
};