validation for schema (middlewares)

VALIDATELISTING IS SENT AS A MIDDLEWARE.


 const ValidateListing = (req, res, next) => {

 
  let { error } = listingSchema.validate(req.body);
  if (error) {
    let errMsg = error.details.map((el) => el.message).join(",");
    throw new ExpressError(400, errMsg);
  } else {
    next();
  }
};
app.post(
  "/listings",ValidateListing,
  wrapAsync(async (req, res, next) => {
   
    const newListing = new Listing(req.body.listing);

    await newListing.save();
    res.redirect("/listings");
  })
);app.put(
  "/listings/:id",ValidateListing,
  wrapAsync(async (req, res) => {
    if (!req.body.listing) {
      throw new ExpressError(400, "send valid data!");
    }
    let { id } = req.params;
    await Listing.findByIdAndUpdate(id, { ...req.body.listing });
    res.redirect(`/listings/${id}`);
  })
);

Comments