MVC FOR LISTINGS
EACH OPERATION IS COPIED AND EXPORTED FROM LISTING.JS(CONTROLLER) TO LISTING.JS(ROUTES)
LISTING.JS(CONTROLLER)
const Listing = require("../models/listing");
module.exports.index = async (req, res) => {
let AllListings = await Listing.find({});
res.render("listings/index.ejs", { AllListings });
};
module.exports.getNewListing = (req, res) => {
res.render("listings/new.ejs");
};
module.exports.postNewListing = async (req, res, next) => {
const newListing = new Listing(req.body.listing);
newListing.owner = req.user._id;
await newListing.save();
req.flash("success", "New Listing Added!");
res.redirect("/listings");
};
module.exports.showListing = async (req, res) => {
let { id } = req.params;
const listing = await Listing.findById(id)
.populate({
path: "reviews",
populate: { path: "author" },
})
.populate("owner");
if (!listing) {
req.flash("error", "Listing requested doesn't exist!");
res.redirect("/listings");
}
res.render("listings/show.ejs", { listing });
};
module.exports.editListing = async (req, res) => {
let { id } = req.params;
const listing = await Listing.findById(id);
if (!listing) {
req.flash("error", "Listing requested doesn't exist!");
res.redirect("/listings");
}
res.render("listings/edit.ejs", { listing });
};
module.exports.updateListing = 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 });
req.flash("success", "Updated Successful!");
res.redirect(`/listings/${id}`);
};
module.exports.deleteListing = async (req, res) => {
let { id } = req.params;
let deletedList = await Listing.findByIdAndDelete(id);
console.log(deletedList);
req.flash("success", "Listing Deleted!");
res.redirect("/listings");
};
LISTING.JS(ROUTES)
const express = require("express");
const router = express.Router();
const wrapAsync = require("../utils/wrapAsync.js");
const ExpressError = require("../utils/ExpressError.js");
const { listingSchema } = require("../schema.js");
const Listing = require("../models/listing.js");
const { isLoggedIn, isOwner, ValidateListing } = require("../middleware.js");
const listingController = require("../controller/listing.js");
// INDEX ROUTE
router.get("/", wrapAsync(listingController.index));
// NEW ROUTE
router.get("/new", isLoggedIn, listingController.getNewListing);
router.post(
"/",
isLoggedIn,
ValidateListing,
wrapAsync(listingController.postNewListing)
);
// SHOW ROUTE
router.get("/:id", wrapAsync(listingController.showListing));
// EDIT ROUTE
router.get(
"/:id/edit",
isLoggedIn,
isOwner,
wrapAsync(listingController.editListing)
);
// UPDATE ROUTE
router.put(
"/:id",
isLoggedIn,
isOwner,
ValidateListing,
wrapAsync(listingController.updateListing)
);
// DELETE ROUTE
router.delete(
"/:id",
isLoggedIn,
isOwner,
wrapAsync(listingController.deleteListing)
);
module.exports = router;
Comments
Post a Comment