From 7e93c013bedea7bdbb5046cc6d3d1280eb9bf4c8 Mon Sep 17 00:00:00 2001 From: George <gm00442@surrey.ac.uk> Date: Tue, 13 Apr 2021 15:04:09 +0100 Subject: [PATCH] Created the create, delete and like posts functions to handle create, delete, and liking posts --- posts-service/controllers/posts.js | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/posts-service/controllers/posts.js b/posts-service/controllers/posts.js index c55d14b..8e0bb30 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) => { -- GitLab