Skip to content

Commit

Permalink
feat:Central messages
Browse files Browse the repository at this point in the history
  • Loading branch information
prateek2102 committed Oct 11, 2024
1 parent 67d4e90 commit f109dc8
Show file tree
Hide file tree
Showing 4 changed files with 151 additions and 115 deletions.
18 changes: 18 additions & 0 deletions constants.js
Original file line number Diff line number Diff line change
@@ -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!"
};
223 changes: 118 additions & 105 deletions controllers/listing.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand All @@ -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");
}
};


Expand All @@ -76,95 +89,95 @@ 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`);
}
};


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");
};
11 changes: 7 additions & 4 deletions controllers/reviews.js
Original file line number Diff line number Diff line change
@@ -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');
}

Expand All @@ -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) =>{
Expand All @@ -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}`);
})
})
14 changes: 8 additions & 6 deletions middlewares/middleware.js
Original file line number Diff line number Diff line change
@@ -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();
Expand All @@ -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();
}
Expand All @@ -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();
}
}

0 comments on commit f109dc8

Please sign in to comment.