-
-
Notifications
You must be signed in to change notification settings - Fork 365
Expand file tree
/
Copy pathconversation.controller.js
More file actions
60 lines (54 loc) · 1.72 KB
/
conversation.controller.js
File metadata and controls
60 lines (54 loc) · 1.72 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
import createError from "../utils/createError.js";
import Conversation from "../models/conversation.model.js";
export const createConversation = async (req, res, next) => {
const newConversation = new Conversation({
id: req.isSeller ? req.userId + req.body.to : req.body.to + req.userId,
sellerId: req.isSeller ? req.userId : req.body.to,
buyerId: req.isSeller ? req.body.to : req.userId,
readBySeller: req.isSeller,
readByBuyer: !req.isSeller,
});
try {
const savedConversation = await newConversation.save();
res.status(201).send(savedConversation);
} catch (err) {
next(err);
}
};
export const updateConversation = async (req, res, next) => {
try {
const updatedConversation = await Conversation.findOneAndUpdate(
{ id: req.params.id },
{
$set: {
// readBySeller: true,
// readByBuyer: true,
...(req.isSeller ? { readBySeller: true } : { readByBuyer: true }),
},
},
{ new: true }
);
res.status(200).send(updatedConversation);
} catch (err) {
next(err);
}
};
export const getSingleConversation = async (req, res, next) => {
try {
const conversation = await Conversation.findOne({ id: req.params.id });
if (!conversation) return next(createError(404, "Not found!"));
res.status(200).send(conversation);
} catch (err) {
next(err);
}
};
export const getConversations = async (req, res, next) => {
try {
const conversations = await Conversation.find(
req.isSeller ? { sellerId: req.userId } : { buyerId: req.userId }
).sort({ updatedAt: -1 });
res.status(200).send(conversations);
} catch (err) {
next(err);
}
};