posts.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import mongoose from "mongoose";
  2. import PostMessage from "../models/postMessage.js";
  3. export const getPosts = async (req, res) => {
  4. try {
  5. const postMessages = await PostMessage.find(); //schema things
  6. res.status(200).json(postMessages.reverse());
  7. } catch (error) {
  8. res.status(404).json({ message: error.message });
  9. }
  10. };
  11. export const createPost = async (req, res) => {
  12. const post = req.body;
  13. debugger
  14. const newPostMessage = new PostMessage({
  15. ...post,
  16. creator: req.userId,
  17. createdAt: new Date().toISOString(),
  18. });
  19. try {
  20. await newPostMessage.save();
  21. res.status(201).json(newPostMessage);
  22. } catch (error) {
  23. res.status(409).json({ message: error.message });
  24. }
  25. };
  26. export const updatePost = async (req, res) => {
  27. const { id } = req.params;
  28. const { title, message, creator, selectedFile } = req.body;
  29. if (!mongoose.Types.ObjectId.isValid(id)) {
  30. return res.status(404).send("No post with that id");
  31. }
  32. const updatedPost = { creator, title, message, selectedFile, _id: id };
  33. await PostMessage.findByIdAndUpdate(id, updatedPost, { new: true });
  34. res.json(updatedPost);
  35. };
  36. export const deletePost = async (req, res) => {
  37. const { id } = req.params;
  38. if (!mongoose.Types.ObjectId.isValid(id)) {
  39. return res.status(404).send("No post with that id");
  40. }
  41. await PostMessage.findByIdAndDelete(id);
  42. res.json({ message: "Post deleted success" });
  43. };
  44. export const likePost = async (req, res) => {
  45. const { id } = req.params;
  46. if (!req.userId) return res.json({ message: "Unauthenticated" });
  47. if (!mongoose.Types.ObjectId.isValid(id)) {
  48. return res.status(404).send("No post with that id");
  49. }
  50. const post = await PostMessage.findById(id);
  51. const index = post.likes.findIndex((id) => id === String(req.userId));
  52. if (index === -1) {
  53. post.likes.push(req.userId);
  54. } else {
  55. post.likes = post.likes.filter((id) => {
  56. return id !== String(req.userId);
  57. });
  58. }
  59. const updatedPost = await PostMessage.findByIdAndUpdate(id, post, {
  60. new: true,
  61. });
  62. res.status(200).json(updatedPost);
  63. };