Tutorial
Posts Routes 3

Post Routes

Routes with Files

This code is a module that handles CRUD operations for posts on a social media website. It includes functions to create, read, and update posts. Here is a breakdown of the code:

Folder Structure

  • The code is organized under the server folder, with a subfolder for controllers and a file for posts.

Imports

  • The code imports two models from separate files, Post.js and User.js.

CREATE

  • The createPost function handles the creation of a new post. It expects data in the request body, including a user ID, a description, and a picture path. It retrieves additional user information from the User model and creates a new Post object with all necessary information. The new post is saved to the database, and all posts are returned to the client as a response.

READ

  • The getFeedPosts function retrieves all posts from the Post model and returns them to the client as a response.
  • The getUserPosts function retrieves all posts from the Post model associated with a specific user ID and returns them to the client as a response.

UPDATE

  • The likePost function updates a post's likes by adding or removing a user's ID to the likes object associated with the post ID. The updated post is then returned to the client as a response.

Overall, the code provides an API for the front-end to handle posts, allowing users to create, view, and like posts on the social media website.

server
├── controllers
│   └── posts.js
server/controllers/posts.js
import Post from "../models/Post.js";
import User from "../models/User.js";
 
/* CREATE */
export const createPost = async (req, res) => {
  try {
    const { userId, description, picturePath } = req.body;
    const user = await User.findById(userId);
    const newPost = new Post({
      userId,
      firstName: user.firstName,
      lastName: user.lastName,
      location: user.location,
      description,
      userPicturePath: user.picturePath,
      picturePath,
      likes: {},
      comments: [],
    });
    await newPost.save();
 
    const post = await Post.find();
    res.status(201).json(post);
  } catch (err) {
    res.status(409).json({ message: err.message });
  }
};
 
/* READ */
export const getFeedPosts = async (req, res) => {
  try {
    const post = await Post.find();
    res.status(200).json(post);
  } catch (err) {
    res.status(404).json({ message: err.message });
  }
};
 
export const getUserPosts = async (req, res) => {
  try {
    const { userId } = req.params;
    const post = await Post.find({ userId });
    res.status(200).json(post);
  } catch (err) {
    res.status(404).json({ message: err.message });
  }
};
 
/* UPDATE */
export const likePost = async (req, res) => {
  try {
    const { id } = req.params;
    const { userId } = req.body;
    const post = await Post.findById(id);
    const isLiked = post.likes.get(userId);
 
    if (isLiked) {
      post.likes.delete(userId);
    } else {
      post.likes.set(userId, true);
    }
 
    const updatedPost = await Post.findByIdAndUpdate(
      id,
      { likes: post.likes },
      { new: true }
    );
 
    res.status(200).json(updatedPost);
  } catch (err) {
    res.status(404).json({ message: err.message });
  }
};

Breakdown

Create Post

export const createPost = async (req, res) => {
  try {
    const { userId, description, picturePath } = req.body;
    const user = await User.findById(userId);
    const newPost = new Post({
      userId,
      firstName: user.firstName,
      lastName: user.lastName,
      location: user.location,
      description,
      userPicturePath: user.picturePath,
      picturePath,
      likes: {},
      comments: [],
    });
    await newPost.save();
 
    const post = await Post.find();
    res.status(201).json(post);
  } catch (err) {
    res.status(409).json({ message: err.message });
  }
};
  • This function creates a new post using the data from the request body. It uses the User and Post models to find the user by their id and create a new post object with their details and the post content. It then saves the new post to the database using await newPost.save().
  • It also finds all the posts from the database using await Post.find() and sends them back as a JSON response with a status code of 201 (created).
  • If there is any error during this process, it catches it and sends back an error message with a status code of 409 (conflict).

Get Feed Posts

export const getFeedPosts = async (req, res) => {
  try {
    const post = await Post.find();
    res.status(200).json(post);
  } catch (err) {
    res.status(404).json({ message: err.message });
  }
};
  • This function gets all the posts from the database using await Post.find() and sends them back as a JSON response with a status code of 200 (ok).
  • If there is any error during this process, it catches it and sends back an error message with a status code of 404 (not found).

Get User Posts

export const getUserPosts = async (req, res) => {
  try {
    const { userId } = req.params;
    const post = await Post.find({ userId });
    res.status(200).json(post);
  } catch (err) {
    res.status(404).json({ message: err.message });
  }
};
  • This function gets all the posts from a specific user using their id from the request parameters. It uses await Post.find({ userId }) to query the database for posts that match the user id. It then sends them back as a JSON response with a status code of 200 (ok).
  • If there is any error during this process, it catches it and sends back an error message with a status code of 404 (not found).

Like Post

export const likePost = async (req, res) => {
  try {
    const { id } = req.params;
    const { userId } = req.body;
    const post = await Post.findById(id);
    const isLiked = post.likes.get(userId);
 
    if (isLiked) {
      post.likes.delete(userId);
    } else {
      post.likes.set(userId, true);
    }
 
    const updatedPost = await Post.findByIdAndUpdate(
      id,
      { likes: post.likes },
      { new: true }
    );
 
   res.status(200).json(updatedPost);
   } catch (err) {
     res.status(404).json({ message: err.message });
   }
 };
  • This function updates the likes of a specific post using its id from the request parameters and the user id from the request body. It uses await Post.findById(id) to find the post by its id and then checks if it is already liked by that user using post.likes.get(userId).
  • If it is already liked, it removes that user’s like using post.likes.delete(userId); otherwise, it adds that user’s like using post.likes.set(userId,true)
  • It then updates the post in the database using await Post.findByIdAndUpdate(id,{likes:post.likes},{new:true}) which returns the updated document as a result. It then sends it back as a JSON response with a status code of 200(ok).
  • If there is any error during this process,it catches it and sends back an error message with a status code of404(not found).