amupedia2021 / amupedia-web

Source code of the website.
https://www.amupedia.site/
MIT License
163 stars 177 forks source link

Refactor Code for Improved Error Handling in Blog.js.route #558

Closed Nishitbaria closed 1 year ago

Nishitbaria commented 1 year ago

Description:

To improve error handling and refactor the code, we can follow some best practices and make the code cleaner and more robust. Below are the suggested improvements:

  1. Centralized Error Handling: Create a middleware function for error handling and use it for all routes to handle errors consistently.

  2. Input Validation: Use a validation library (like Joi) to validate the input data and ensure that the required fields are provided with valid data.

  3. Use Async/Await and Try/Catch: Use async/await and try/catch blocks for better readability and to handle asynchronous code and potential errors gracefully.

  4. Refactor Repeated Code: Refactor the code to remove duplicated lines and improve the overall structure.

Suggested Code Changes:

Here's the refactored code with the suggested improvements:

const router = require("express").Router();
const User = require("../model/user.model");
const Blog = require("../model/blog.model");
const Joi = require("joi"); // Assuming you have Joi installed

// Centralized Error Handling Middleware
function errorHandler(res, err) {
  console.error(err);
  res.status(500).json({ error: "Something went wrong" });
}

const isLoggedIn = (req, res, next) => {
  if (req.session.userId) {
    next();
  } else {
    res.status(401).json({ error: "Unauthorized" });
  }
};

// Input validation schema for blog creation and update
const blogSchema = Joi.object({
  title: Joi.string().required(),
  desc: Joi.string().required(),
});

//CREATE BLOG
router.post("/", isLoggedIn, async (req, res) => {
  try {
    const { error } = blogSchema.validate(req.body);
    if (error) {
      return res.status(400).json({ error: "Must have Title and Description" });
    }

    const user = await User.findById(req.session.userId);
    const newBlog = new Blog({
      title: req.body.title,
      desc: req.body.desc,
      username: user.username,
    });
    const savedBlog = await newBlog.save();
    res.status(200).json(savedBlog);
  } catch (err) {
    errorHandler(res, err);
  }
});

//UPDATE BLOG
router.put("/:id", isLoggedIn, async (req, res) => {
  try {
    const blog = await Blog.findById(req.params.id);
    if (!blog) {
      return res.status(404).json({ error: "Blog not found" });
    }

    const user = await User.findById(req.session.userId);
    if (blog.username !== user.username) {
      return res.status(401).json({ error: "You can update only your Blog!" });
    }

    const updatedBlog = await Blog.findByIdAndUpdate(
      req.params.id,
      { $set: req.body },
      { new: true }
    );
    res.status(200).json(updatedBlog);
  } catch (err) {
    errorHandler(res, err);
  }
});

//DELETE BLOG
router.delete("/:id", isLoggedIn, async (req, res) => {
  try {
    const blog = await Blog.findById(req.params.id);
    if (!blog) {
      return res.status(404).json({ error: "Blog not found" });
    }

    const user = await User.findById(req.session.userId);
    if (blog.username !== user.username) {
      return res.status(401).json({ error: "You can delete only your blog!" });
    }

    await blog.delete();
    res.status(200).json("Blog has been deleted...");
  } catch (err) {
    errorHandler(res, err);
  }
});

//GET BLOG
router.get("/:id", async (req, res) => {
  try {
    const blog = await Blog.findById(req.params.id);
    if (!blog) {
      return res.status(404).json({ error: "Blog not found" });
    }
    res.status(200).json(blog);
  } catch (err) {
    errorHandler(res, err);
  }
});

//GET ALL BLOG
router.get("/", async (req, res) => {
  try {
    const blogs = await Blog.find();
    res.status(200).json(blogs);
  } catch (err) {
    errorHandler(res, err);
  }
});

module.exports = router;

With these changes, the code now handles errors more efficiently and provides better validation for creating and updating blogs. It also avoids duplicated error handling code by using the errorHandler middleware.

Please review the changes and let me know if you have any questions or concerns.

github-actions[bot] commented 1 year ago

Hello @Nishitbaria! Thank you for raising this issue.

Please make sure to follow our Contributing Guidelines. πŸ’ͺ🏻 Don't forget to ⭐ our Project-Amupedia. πŸ“”

Our review team will carefully assess the issue and reach out to you soon! πŸ˜‡ We appreciate your patience! πŸ˜€

github-actions[bot] commented 1 year ago

This issue is stale because it has been open for 14 days with no activity.