DEV Community

Akash Singh
Akash Singh

Posted on

Day 17 Progress Journal: Implementing Like and Unlike Backend API (MERN Stack Instagram Clone)

Today's achievement focused on developing the backend API for the like and unlike feature, which is essential for our Instagram clone. This functionality enables users to engage with posts by liking or unliking them, thereby boosting user interaction.

Steps and Achievements:

  1. Database Schema Enhancements:

    • Modified the Post Schema in MongoDB to incorporate a likes field as an array, allowing us to track the IDs of users who have liked a particular post.
    • Improved querying and updates by indexing the likes field for better performance.
  2. API Endpoints:

    • POST /posts/:id/like:
      • Developed logic to append the user's ID to the likes array if it isn't already included.
      • Returned the updated like count along with a confirmation message.
    • POST /posts/:id/unlike:
      • Created logic to remove the user's ID from the likes array if it exists.
      • Returned the updated like count and a confirmation message.
  3. Validation and Error Management:

    • Implemented middleware to validate authentication tokens, ensuring that only authenticated users can like or unlike posts.
    • Addressed edge cases such as:
      • Attempting to like a post that has already been liked.
      • Trying to unlike a post that hasn't been liked.
      • Handling invalid or non-existent post IDs.
  4. Performance Improvements:

    • Utilized MongoDB's $addToSet operator for adding unique likes and $pull for removing likes, minimizing unnecessary checks.
    • Conducted latency tests on the API under multiple concurrent requests to ensure it can scale effectively.
  5. Test-Driven Development:

    • Developed test cases to verify API functionality, including:
      • Successful like and unlike actions.
      • Responses to invalid post IDs.
      • Handling unauthorized access attempts.

Reflections and Insights:

This session highlighted the significance of efficient database architecture and strong API development practices. The addition of like and unlike functionality introduced a layer of interactivity to the application, enhancing user engagement. By following the principles of Test-Driven Development, we ensured a reliable and robust implementation.

Top comments (0)