-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddComment.js
55 lines (47 loc) · 1.48 KB
/
addComment.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import redis from '../../lib/redisClient';
import { v4 as uuidv4 } from 'uuid';
export default async function addComment(req, res) {
if (req.method !== 'POST') {
res.setHeader('Allow', ['POST']);
return res.status(405).json({ success: false, message: `Method ${req.method} Not Allowed` });
}
const { course, postId, uid } = req.query;
const { text, email } = req.body;
if (!course || !postId || !uid) {
return res.status(400).json({ success: false, message: "Course, postId, and uid are required." });
}
if (!text || !text.trim()) {
return res.status(400).json({ success: false, message: "Comment text is required." });
}
if (!email || !email.trim()) {
return res.status(400).json({ success: false, message: "Email is required." });
}
try {
const commentId = uuidv4();
const time = new Date().toISOString();
const comment = {
time,
uid,
text: text.trim(),
email: email.trim(), // Store the email in the comment object
upvotes: 0,
downvotes: 0,
};
await redis.hset(
`courses:${course}:posts:${postId}:comments`,
commentId,
JSON.stringify(comment)
);
return res.status(200).json({
success: true,
message: "Comment added successfully.",
data: {
commentId,
...comment,
},
});
} catch (error) {
console.error("Error adding comment:", error);
return res.status(500).json({ success: false, message: "Internal Server Error." });
}
}