fedect1 / graduation-project-fedect1

graduation-project-fedect1 created by GitHub Classroom
MIT License
1 stars 0 forks source link

#CleanCode Backend #16

Open Dr4gon opened 1 year ago

Dr4gon commented 1 year ago

@fedect1 Wow. The error handling in the backend is very thorough even with appropriate HTTP status codes as well a catch all. Keep that up. It will save you a lot of trouble and make your customers happy.

posts.js

//DELETE
/* Delete a post */
router.delete('/:postId/:userId', async function (req, res, next) {
  try {
    // Find the user
    const user = await User.findById(req.params.userId)
    if (!user) {
      return res.status(404).send({ message: 'User not found' })
    }

    // Find the post index in the user's posts array
    await user.deletePost(req.params.postId)

    // Delete the post from the posts collection
    const deletedPost = await Post.findByIdAndDelete(req.params.postId)
    if (!deletedPost) {
      return res.status(404).send({ message: 'Post not found in collection' })
    }

    // Send the response
    res.send({ message: 'Post deleted successfully' })
  } catch (error) {
    next(error)
  }
})