55 lines
1.4 KiB
JavaScript
55 lines
1.4 KiB
JavaScript
import Blog from "../models/blog.model.js";
|
|
|
|
// Add comment to a blog
|
|
export const addComment = async (req, res) => {
|
|
try {
|
|
const { blogId } = req.params;
|
|
const { text, name } = req.body;
|
|
|
|
const blog = await Blog.findById(blogId);
|
|
if (!blog) return res.status(404).json({ message: "Blog not found" });
|
|
|
|
blog.comments.push({
|
|
user: req.user?._id || null,
|
|
name: name || "Anonymous",
|
|
text
|
|
});
|
|
|
|
await blog.save();
|
|
res.status(201).json(blog.comments);
|
|
} catch (err) {
|
|
res.status(500).json({ message: err.message });
|
|
}
|
|
};
|
|
|
|
// Get all comments for a blog
|
|
export const getComments = async (req, res) => {
|
|
try {
|
|
const { blogId } = req.params;
|
|
|
|
const blog = await Blog.findById(blogId);
|
|
if (!blog) return res.status(404).json({ message: "Blog not found" });
|
|
|
|
res.json(blog.comments.sort((a,b) => b.createdAt - a.createdAt));
|
|
} catch (err) {
|
|
res.status(500).json({ message: err.message });
|
|
}
|
|
};
|
|
|
|
// Delete a comment (Admin only)
|
|
export const deleteComment = async (req, res) => {
|
|
try {
|
|
const { blogId, commentId } = req.params;
|
|
|
|
const blog = await Blog.findById(blogId);
|
|
if (!blog) return res.status(404).json({ message: "Blog not found" });
|
|
|
|
blog.comments.id(commentId)?.remove();
|
|
await blog.save();
|
|
|
|
res.json({ message: "Comment deleted" });
|
|
} catch (err) {
|
|
res.status(500).json({ message: err.message });
|
|
}
|
|
};
|