Skip to content

Commit

Permalink
now you can add, view, delete reviews to a particular campground
Browse files Browse the repository at this point in the history
  • Loading branch information
moonpatel committed Aug 30, 2022
1 parent 481b4bd commit 54b682c
Show file tree
Hide file tree
Showing 4 changed files with 92 additions and 39 deletions.
37 changes: 29 additions & 8 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ const catchAsync = require('./utils/catchAsync')
const ExpressError = require('./utils/ExpressError')
// require models
const Campground = require('./models/campgrounds')
const Review = require('./models/reviews')
const { campgroundSchema } = require('./schemas')
const joi = require('joi')
const { reviewSchema } = require('./schemas')
// port number to listen for requests
const port = 3000

Expand All @@ -19,7 +20,7 @@ mongoose.connect('mongodb://localhost:27017/yelpcamp')
// check the status of database connection
const db = mongoose.connection
db.on("error", console.error.bind(console, "connection error"))
db.once("open", () => console.log("Database connected"))
db.once("open", () => console.log("Connected to MongoDB"))

// create an express application object
const app = express()
Expand All @@ -37,7 +38,16 @@ const validateCampground = (req, res, next) => {
const { error } = campgroundSchema.validate(req.body.campground)
if (error) {
const msg = error.details.map(el => el.message).join(',')
next(new ExpressError(msg, 400))
throw new ExpressError(msg, 400)
}
else next()
}
// validate reviews object
const validateReview = (req, res, next) => {
const { error } = reviewSchema.validate(req.body.review)
if (error) {
const msg = error.details.map(el => el.message).join(',')
throw new ExpressError(msg, 400)
}
else next()
}
Expand All @@ -60,9 +70,24 @@ app.post('/campgrounds', validateCampground, catchAsync(async (req, res, next) =
await cg.save()
res.redirect(`/campgrounds/${cg._id}`)
}))
// add review to server
app.post('/campgrounds/:id/reviews', validateReview, catchAsync(async (req, res) => {
const campground = await Campground.findById(req.params.id)
const review = new Review(req.body.review)
campground.reviews.push(review)
await campground.save()
await review.save()
res.redirect(`/campgrounds/${req.params.id}`)
}))
app.delete('/campgrounds/:id/reviews/:reviewId',catchAsync(async (req,res,next) => {
const {id,reviewId} = req.params
await Review.findByIdAndDelete(reviewId)
await Campground.findByIdAndUpdate(id, {$pull: {reviews: reviewId}})
res.redirect(`/campgrounds/${id}`)
}))
// show individual campground
app.get('/campgrounds/:id', catchAsync(async (req, res) => {
const c = await Campground.findOne({ _id: req.params.id })
const c = await Campground.findOne({ _id: req.params.id }).populate('reviews')
res.render('campgrounds/show', { c })
}))
// render form to edit a campground
Expand All @@ -81,19 +106,15 @@ app.delete('/campgrounds/:id', catchAsync(async (req, res) => {
await Campground.findByIdAndDelete(req.params.id)
res.redirect('/campgrounds')
}))


// if page unavailable
app.all('*', (req, res, next) => {
next(new ExpressError('Page not found', 404))
})

// error handler
app.use((err, req, res, next) => {
const { message = 'Something went wrong', statusCode = 500 } = err
console.log(err)
res.status(statusCode).render('error', { err })
})

// listen for incoming requests
app.listen(port, () => console.log(`LISTENING ON PORT ${port}`))
8 changes: 7 additions & 1 deletion schemas.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,10 @@ const campgroundSchema = joi.object({
description: joi.string().required(),
image: joi.string().required()
}).required()
module.exports.campgroundSchema = campgroundSchema
module.exports.campgroundSchema = campgroundSchema

const reviewSchema = joi.object({
body: joi.string().required(),
rating: joi.number().required().min(0).max(5)
}).required()
module.exports.reviewSchema = reviewSchema
84 changes: 54 additions & 30 deletions views/campgrounds/show.ejs
Original file line number Diff line number Diff line change
@@ -1,42 +1,66 @@
<% layout('layouts/boilerplate.ejs') %>
<div class="row">
<div class="card px-0 mb-3">
<img src="<%= c.image %>/900x600" alt="campground" class="card-img-top">
<div class="card-body">
<h5 class="card-title mb-0">
<%= c.title %>
</h5>
<small class="text-muted">
<%=c.location%>
</small>
<p class="card-text mt-3">
<%=c.description%>
</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">$<%=c.price%>/night</li>
</ul>
<div class="card-body">
<!-- <a class="btn btn-primary" href="/campgrounds">Back</a> -->
<a class="btn btn-primary" href="/campgrounds/<%= c._id %>/edit">Edit</a>
<form action="/campgrounds/<%= c._id %>?_method=DELETE" method="post" class="mt-2 d-inline">
<button class="btn btn-danger">Delete</button>
</form>
<div class="col-6">
<div class="card px-0 mb-3">
<img src="<%= c.image %>/900x600" alt="campground" class="card-img-top">
<div class="card-body">
<h5 class="card-title mb-0">
<%= c.title %>
</h5>
<small class="text-muted">
<%=c.location%>
</small>
<p class="card-text mt-3">
<%=c.description%>
</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">$<%=c.price%>/night</li>
</ul>
<div class="card-body">
<a class="btn btn-primary" href="/campgrounds/<%= c._id %>/edit">Edit</a>
<form action="/campgrounds/<%= c._id %>?_method=DELETE" method="post" class="mt-2 d-inline">
<button class="btn btn-danger">Delete</button>
</form>
</div>

</div>
</div>
<div class="col-6">
<div>
<form action="">
<h2>Leave a Review</h2>
<form action="/campgrounds/<%= c._id %>/reviews" method="post" class="mb-3 validated-form" novalidate>
<div class="mb-3">
<label for="rating">Rating</label>
<input class="form-label" type="range" min="1" max="5" name="review[range]">
<label class="form-label" for="rating">Rating</label>
<input class="form-range" type="range" min="1" max="5" name="review[rating]" id="rating"
value="0" required>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Looks bad!</div>
</div>
<div class="mb-3">
<label class="form-label" for="body">Review</label>
<textarea name="review[body]" id="body" cols="30" rows="3"></textarea>
<textarea class="form-control" name="review[body]" id="body" cols="30" rows="3" value=""
required></textarea>
<div class="valid-feedback">Looks good!</div>
<div class="invalid-feedback">Looks bad!</div>
</div>
<!-- <button>Submit</button> -->
<button class="btn btn-success">Submit</button>
</form>
<%for(let review of c.reviews) {%>
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title mb-0">
Rating: <%= review.rating %>
</h5>
<p class="card-text mt-3">
<%= review.body %>
</p>
<form action="/campgrounds/<%=c._id%>/reviews/<%=review._id%>?_method=DELETE" method="post">
<button class="btn btn-sm btn-danger">Delete</button>
</form>
</div>
</div>
<%}%>
</div>
</div>
</div>

<!-- on branch cookies -->
</div>
2 changes: 2 additions & 0 deletions views/layouts/boilerplate.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,13 @@
// Fetch all the forms we want to apply custom Bootstrap validation styles to
const forms = document.querySelectorAll('.validated-form')
console.log(forms)
// Loop over them and prevent submission
Array.from(forms)
.forEach(form => {
form.addEventListener('submit', event => {
console.log('inside validation')
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
Expand Down

0 comments on commit 54b682c

Please sign in to comment.