From f109dc82ccb8a3f57b72dcc329967682b49ea5f9 Mon Sep 17 00:00:00 2001 From: Prateek Date: Sat, 12 Oct 2024 01:10:08 +0530 Subject: [PATCH] feat:Central messages --- constants.js | 18 +++ controllers/listing.js | 223 ++++++++++++++++++++------------------ controllers/reviews.js | 11 +- middlewares/middleware.js | 14 ++- 4 files changed, 151 insertions(+), 115 deletions(-) create mode 100644 constants.js diff --git a/constants.js b/constants.js new file mode 100644 index 0000000..eb38cb9 --- /dev/null +++ b/constants.js @@ -0,0 +1,18 @@ +// constants.js +module.exports = { + ERROR_LOGIN_REQUIRED: "You must login", + ERROR_NO_PERMISSION: "You don't have permission", + ERROR_NOT_AUTHOR: "You are not the Author", + ERROR_FETCH_LISTINGS: "Failed to fetch listings. Please try again later.", + ERROR_CREATE_LISTING: "Failed to create listing", + ERROR_LOAD_EDIT_PAGE: "Failed to load edit page", + ERROR_LOAD_LISTING_DETAILS: "Failed to load listing details", + ERROR_UPDATE_LISTING: "Failed to update listing", + ERROR_DELETE_LISTING: "Failed to delete listing", + ERROR_LISTING_NOT_FOUND: "Listing not found", + ERROR_SEND_VALID_DATA: "Send valid data of listing", + SUCCESS_LISTING_CREATED: "New listing created successfully", + SUCCESS_LISTING_UPDATED: "Listing updated successfully", + SUCCESS_LISTING_DELETED: "Listing deleted successfully", + SUCCESS_REVIEW_ADDED: "Review added successfully!" +}; \ No newline at end of file diff --git a/controllers/listing.js b/controllers/listing.js index d236851..53159cd 100644 --- a/controllers/listing.js +++ b/controllers/listing.js @@ -3,17 +3,30 @@ const mbxgeocoding = require('@mapbox/mapbox-sdk/services/geocoding'); const maptoken = process.env.MAP_TOKEN; const geocodingClient = mbxgeocoding({ accessToken: maptoken }); const cloudinary = require('cloudinary').v2; +const { + ERROR_FETCH_LISTINGS, + ERROR_CREATE_LISTING, + ERROR_LOAD_EDIT_PAGE, + ERROR_LOAD_LISTING_DETAILS, + ERROR_UPDATE_LISTING, + ERROR_DELETE_LISTING, + ERROR_LISTING_NOT_FOUND, + ERROR_SEND_VALID_DATA, + SUCCESS_LISTING_CREATED, + SUCCESS_LISTING_UPDATED, + SUCCESS_LISTING_DELETED, +} = require('../constants.js'); module.exports.index = async (req, res) => { - try { - const listings = await listing.find(); - console.log("Listings fetched:", listings); - res.render("index.ejs", { listings }); - } catch (err) { - console.error("Error fetching listings:", err); - req.flash("error", "Failed to fetch listings. Please try again later."); - return res.redirect("/"); - } + try { + const listings = await listing.find(); + console.log("Listings fetched:", listings); + res.render("index.ejs", { listings }); + } catch (err) { + console.error("Error fetching listings:", err); + req.flash("error", ERROR_FETCH_LISTINGS); + return res.redirect("/"); + } }; module.exports.newpost = async (req, res) => { @@ -22,52 +35,52 @@ module.exports.newpost = async (req, res) => { }; module.exports.createpost = async (req, res) => { - try { + try { // Validate that listing data exists - if (!req.body.listing) { - return res.status(404).send("Enter valid listing details"); - } + if (!req.body.listing) { + return res.status(404).send(ERROR_SEND_VALID_DATA); + } - const { title, description, price, country, location } = req.body.listing; + const { title, description, price, country, location } = req.body.listing; // Geocoding to get coordinates from location - const geoData = await geocodingClient.forwardGeocode({ - query: location, - limit: 1 - }).send(); - - const newListing = new listing({ - title, - description, - price, - country, - location, - geometry: geoData.body.features[0].geometry, - owner: req.user._id, - image: [] - }); + const geoData = await geocodingClient.forwardGeocode({ + query: location, + limit: 1 + }).send(); + + const newListing = new listing({ + title, + description, + price, + country, + location, + geometry: geoData.body.features[0].geometry, + owner: req.user._id, + image: [] + }); // Handle multiple image uploads from Cloudinary - if (req.files) { - req.files.forEach(file => { - newListing.image.push({ - url: file.path, - filename: file.filename - }); - }); - } + if (req.files) { + req.files.forEach(file => { + newListing.image.push({ + url: file.path, + filename: file.filename + }); + }); + } // Save the listing to the database - await newListing.save(); + await newListing.save(); - req.flash("success", "New listing created successfully"); - return res.redirect("/listing"); + req.flash("success", SUCCESS_LISTING_CREATED); + return res.redirect("/listing"); - } catch (err) { - console.error(err); - req.flash("error", "Failed to create listing"); - return res.redirect("/listing/new"); - } + } catch (err) { + console.error(err); + req.flash("error", ERROR_CREATE_LISTING); + return res.redirect("/listing/new"); + } }; @@ -76,84 +89,84 @@ module.exports.editpost = async (req, res) => { const { id } = req.params; const list = await listing.findById(id); if (!list) { - req.flash('error', 'Listing not found'); + req.flash('error', ERROR_LISTING_NOT_FOUND); return res.redirect('/listing'); } res.render("edit.ejs", { list }); } catch (err) { console.error(err); - req.flash("error", "Failed to load edit page"); + req.flash("error", ERROR_LOAD_EDIT_PAGE); return res.redirect("/listing"); } }; module.exports.showPost = async (req, res) => { - try { - const { id } = req.params; - const list = await listing.findById(id) - .populate({ - path: 'reviews', - populate: { - path: 'author' - } - }) - .populate('owner'); - - console.log(list); - - if (!list) { - req.flash('error', 'Listing not found'); - return res.redirect('/listing'); - } - - res.render('show.ejs', { list }); - } catch (err) { - console.error("Error fetching listing:", err); - req.flash("error", "Failed to load listing details"); - return res.redirect("/listing"); - } + try { + const { id } = req.params; + const list = await listing.findById(id) + .populate({ + path: 'reviews', + populate: { + path: 'author' + } + }) + .populate('owner'); + + console.log(list); + + if (!list) { + req.flash('error', ERROR_LISTING_NOT_FOUND); + return res.redirect('/listing'); + } + + res.render('show.ejs', { list }); + } catch (err) { + console.error("Error fetching listing:", err); + req.flash("error", ERROR_LOAD_LISTING_DETAILS); + return res.redirect("/listing"); + } }; module.exports.saveEditpost = async (req, res) => { - const { id } = req.params; + const { id } = req.params; - try { - if (!req.body.listing) { - req.flash('error', 'Send valid data of listing'); - return res.redirect(`/listing/${id}`); - } + try { + if (!req.body.listing) { + req.flash('error', ERROR_SEND_VALID_DATA); + return res.redirect(`/listing/${id}`); + } - let editList = await listing.findById(id); + let editList = await listing.findById(id); - if (req.files && req.files.length > 0) { - editList.image = []; + if (req.files && req.files.length > 0) { + editList.image = []; - req.files.forEach(file => { + req.files.forEach(file => { // Upload to Cloudinary and get the URL - editList.image.push({ - url: file.path, - filename: file.filename - }); - }); - } + editList.image.push({ + url: file.path, + filename: file.filename + }); + }); + } // Update other fields - editList.title = req.body.listing.title; - editList.description = req.body.listing.description; - editList.price = req.body.listing.price; - editList.location = req.body.listing.location; - editList.country = req.body.listing.country; - - await editList.save(); - - req.flash('success', 'Listing updated successfully'); - return res.redirect(`/listing/${id}`); - - } catch (err) { - console.error(err); - req.flash("error", "Failed to update listing"); - return res.redirect(`/listing/${id}/edit`); - } + editList.title = req.body.listing.title; + editList.description = req.body.listing.description; + editList.price = req.body.listing.price; + editList.location = req.body.listing.location; + editList.country = req.body.listing.country; + + await editList.save(); + + req.flash('success', SUCCESS_LISTING_UPDATED); + return res.redirect(`/listing/${id}`); + + } catch (err) { + console.error(err); + req.flash("error", ERROR_UPDATE_LISTING); + return res.redirect(`/listing/${id}/edit`); + } }; @@ -161,10 +174,10 @@ module.exports.deletepost = async (req, res) => { const { id } = req.params; try { await listing.findByIdAndDelete(id); // Deconstructing parameters - req.flash("success", "Listing deleted successfully"); + req.flash("success", SUCCESS_LISTING_DELETED); } catch (err) { console.error(err); - req.flash("error", "Failed to delete listing"); + req.flash("error", ERROR_DELETE_LISTING); } res.redirect("/listing"); }; diff --git a/controllers/reviews.js b/controllers/reviews.js index 05f68cf..cb98c0e 100644 --- a/controllers/reviews.js +++ b/controllers/reviews.js @@ -1,12 +1,15 @@ const review=require("../models/reviews.js"); const listing=require("../models/listing.js"); - +const { + SUCCESS_REVIEW_ADDED, + ERROR_LISTING_NOT_FOUND +} = require('../constants.js') module.exports.reviewPost = (async (req, res) => { const { id } = req.params; const list = await listing.findById(id); if (!list) { - req.flash('error', 'Listing not found'); + req.flash('error', ERROR_LISTING_NOT_FOUND); return res.redirect('/listing'); } @@ -17,7 +20,7 @@ module.exports.reviewPost = (async (req, res) => { await newReview.save(); await list.save(); - req.flash('success', 'Review added successfully!'); + req.flash('success', SUCCESS_REVIEW_ADDED); res.redirect(`/listing/${list._id}`); }); module.exports.deleteReview =(async (req,res) =>{ @@ -26,4 +29,4 @@ module.exports.deleteReview =(async (req,res) =>{ await listing.findByIdAndUpdate(id,{$pull:{reviews:rid}}); //update the listing-reviews array where review id matched rid await review.findByIdAndDelete(rid); //deconstructing parameters res.redirect(`/listing/${id}`); - }) +}) diff --git a/middlewares/middleware.js b/middlewares/middleware.js index fd13135..04281d3 100644 --- a/middlewares/middleware.js +++ b/middlewares/middleware.js @@ -1,10 +1,11 @@ const listing=require("../models/listing.js"); const reviews=require("../models/reviews.js"); +const { ERROR_LOGIN_REQUIRED, ERROR_NO_PERMISSION, ERROR_NOT_AUTHOR } = require('../constants.js'); module.exports.isLoggedIn=(req,res,next) =>{ if(!req.isAuthenticated()) { req.session.redirectUrl=req.originalUrl; - req.flash("error","You must login"); + req.flash("error",ERROR_LOGIN_REQUIRED); return res.redirect("/login"); } next(); @@ -21,8 +22,8 @@ module.exports.saveRedirectUrl=(req,res,next) =>{ let {id} =req.params; const editList = await listing.findById(id); if (!req.user || !editList.owner._id.equals(res.locals.currUser._id)) { - req.flash('error', "You don't have permission"); - return res.redirect(`/listing/${id}`); + req.flash('error', ERROR_NO_PERMISSION); + return res.redirect(`/listing/${id}`); } next(); } @@ -31,8 +32,9 @@ module.exports.saveRedirectUrl=(req,res,next) =>{ let {id,rid} =req.params; const review = await reviews.findById(rid); if (!review.author.equals(res.locals.currUser._id)) { - req.flash('error', "You are not the Author"); - return res.redirect(`/listing/${id}`); + req.flash('error', ERROR_NOT_AUTHOR); + return res.redirect(`/listing/${id}`); } next(); -} + } + \ No newline at end of file