-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
140 lines (115 loc) · 3.74 KB
/
Copy pathapp.js
File metadata and controls
140 lines (115 loc) · 3.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
require('dotenv').config();
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const Listing = require("./models/listing.js");
const path = require("path");
const methodOverride=require('method-override');
const ejsMate= require('ejs-mate')
//ejs-mate: use same parts of code in different pages
const ExpressError = require("./utils/expressError.js")
const wrapAsync=require("./utils/wrapAsync.js")
let User = require("./models/user.js");
const listingRouter=require("./routes/listing.js");
const Review =require("./models/review.js");
const session = require("express-session");
const flash = require("connect-flash");
const cookieParser=require("cookie-parser");
const userRouter = require("./routes/user.js");
const authMiddleware = require("./middlewares/authMiddleware.js")
const reviewOwner = require("./middlewares/reviewOwner.js");
const { log } = require('console');
const MONGO_URL = "mongodb://127.0.0.1:27017/myDestination";
main()
.then(() => {
console.log("connected to DB");
})
.catch((err) => {
console.log(err);
});
async function main() {
await mongoose.connect(MONGO_URL);
}
app.set("view engine","ejs");
app.set("views",path.join(__dirname,"views"))
app.use(express.urlencoded({extended:true}))
app.use(methodOverride("_method"));
app.use(express.static(path.join(__dirname, "/public")));
app.use(cookieParser());
app.use(session({
secret:'secretKey',
resave:false,
saveUninitialized:false
}));
app.use(flash());
//flash middle ware
app.use((req,res,next)=>{
res.locals.success_msg=req.flash('success')
res.locals.success_msg=req.flash('failed')
next();
})
app.engine('ejs',ejsMate);
/*app.use((req,res,next)=>{
res.locals.success=req.flash("success");
res.locals.error=req.flash("error")
next();
})
*/
// app.get("/demouser",async(req,res)=>{
// let fakeUser=new User({
// email:"sunetra@gmail.com",
// username:"dipu",
// })
// let registeredUser= await User.register(fakeUser,"Bar@1234");
// res.send(registeredUser);
// })
app.use("/listings",listingRouter)
app.use("/",userRouter)
app.get("/",async (req, res) => {
const allListings=await Listing.find({})
res.render("./listings/homePage.ejs",{allListings});
});
// app.get("/testListing", async (req, res) => {
// let sampleListing = new Listing({
// title: "My New Villa",
// description: "By the beach",
// price: 1200,
// location: "Calangute, Goa",
// country: "India",
// });
// await sampleListing.save();
// console.log("sample was saved");
// res.send("successful testing");
// });
//reviews
//post route
app.post("/listings/:id/reviews",authMiddleware,async(req,res)=>{
let listing=await Listing.findById(req.params.id);
let user=await User.findById(req.userId);
let newReview=new Review(req.body.review);
newReview.author=req.userId;
listing.reviews.push(newReview);
await newReview.save();
user.myReviews.push(newReview._id);
await listing.save();
await user.save();
res.redirect(`/listings/${listing._id}`);
});
//delete review route
// mongo $pull operator:remove from an existing array all instance of a value or values that match a specified condition
app.delete("/listings/:id/reviews/:reviewId",reviewOwner,wrapAsync(async(req,res)=>{
let {id , reviewId}=req.params;
await Listing.findByIdAndUpdate(id, {$pull: {reviews: reviewId}});
await Review.findByIdAndDelete(reviewId);
res.redirect(`/listings/${id}`)
})) ;
app.all("/*splat",(req,res,next)=>{
next(new ExpressError(404,"page not found!"))
});
app.use((err,req,res,next)=>{
let {statusCode=500,message="something went wrong!"}=err;
res.status(statusCode).render("error.ejs",{err})
});
app.listen(8080, () => {
console.log("server is listening to port 8080");
});