RESTRUCTURING LISTINGS
A ROUTER FOLDER IS CREATED AND A LISTING.JS FILE IS CREATED IN IT.
LISTING.JS
const express = require("express");
const router = express.Router();
const wrapAsync = require("../utils/wrapAsync.js");
const ExpressError = require("../utils/ExpressError.js");
const { listingSchema, reviewSchema } = require("../schema.js");
const Listing = require("../models/listing.js");
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();
}
};
// INDEX ROUTE
router.get(
"/",
wrapAsync(async (req, res) => {
let AllListings = await Listing.find({});
res.render("listings/index.ejs", { AllListings });
})
);
// NEW ROUTE
router.get("/new", (req, res) => {
res.render("listings/new.ejs");
});
router.post(
"/",
ValidateListing,
wrapAsync(async (req, res, next) => {
const newListing = new Listing(req.body.listing);
await newListing.save();
res.redirect("/listings");
})
);
// SHOW ROUTE
router.get(
"/:id",
wrapAsync(async (req, res) => {
let { id } = req.params;
const listing = await Listing.findById(id).populate("reviews");
res.render("listings/show.ejs", { listing });
})
);
// EDIT ROUTE
router.get(
"/:id/edit",
wrapAsync(async (req, res) => {
let { id } = req.params;
const listing = await Listing.findById(id);
res.render("listings/edit.ejs", { listing });
})
);
// UPDATE ROUTE
router.put(
"/: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}`);
})
);
// DELETE ROUTE
router.delete(
"/:id",
wrapAsync(async (req, res) => {
let { id } = req.params;
let deletedList = await Listing.findByIdAndDelete(id);
console.log(deletedList);
res.redirect("/listings");
})
);
module.exports=router;
ALL THE ROUTES WITH /listings ARE COPIED AND ALL THE REQUIRED CONSTANTS AND FUNCTIONS ARE ALSO COPIED(WrapAsync and ValidateListing)
router IS EXPORTED.
IN APP.JS router IS REQUIRED.
const listings = require("./routes/listings.js");
app.use("/listings", listings);
BY THESE TWO LINES /listings CAN BE USED.



Comments
Post a Comment