diff --git a/posts-service/controllers/posts.js b/posts-service/controllers/posts.js index c55d14b08c8586dc6315f48ac4f36e5c4c63b713..8e0bb30a1dacb14a1d499d3cd87d2fe8d5236340 100644 --- a/posts-service/controllers/posts.js +++ b/posts-service/controllers/posts.js @@ -11,7 +11,14 @@ export const getPosts = async (req, res) => { }; export const createPost = async (req, res) => { - + const post = new Post({ ...req.body, createdAt: new Date().toISOString() }); + + try { + await post.save(); + return res.status(201).json(post); + } catch (error) { + return res.status(409).json({ message: "Something went wrong" }); + } } export const getPostById = async (req, res) => { @@ -26,11 +33,26 @@ export const getPostById = async (req, res) => { } export const deletePost = async (req, res) => { - + const { id } = req.params; + + if (!mongoose.Types.ObjectId.isValid(id)) return res.status(404).send(`No post with id: ${id}`); + + await Post.findByIdAndRemove(id); + return res.status(200).json({ message: "Post Deleted" }); } export const likePost = async (req, res) => { - + const { id, userId } = req.params; + const post = await Post.findById(id); + + if (post.likes.find((like) => like === userId)) { + post.likes = post.likes.filter((like) => like !== userId); + } else { + post.likes.push(userId); + } + + await post.save(); + return res.status(200).json(post); } export const addComment = async (req, res) => {