-Breaking Out Campground Routes
-Breaking Out Review Routes
-Configuring Session
-Setting Up Flash
-Flash Success Partial
Breaking Out Campground Routes
Updating the routes and putting them in their own campgrounds.js file
const express = require('express');
const router = express.Router();
const catchAsync = require('../utils/catchAsync');
const { campgroundSchema } = require('../schemas.js');
const ExpressError = require('../utils/ExpressError');
const Campground = require('../models/campground');
const validateCampground = (req, res, next) => {
const { error } = campgroundSchema.validate(req.body);
if (error) {
const msg = error.details.map(el => el.message).join(',')
throw new ExpressError(msg, 400)
} else {
next();
}
}
router.get('/', catchAsync(async (req, res) => {
const campgrounds = await Campground.find({});
res.render('campgrounds/index', { campgrounds })
}));
router.get('/campgrounds/new', (req, res) => {
res.render('campgrounds/new');
})
router.post('/campgrounds', validateCampground, catchAsync(async (req, res)
Breaking Out Review Routes
Creating a reviews.js to put the review code in.
const express = require('express');
const router = express.Router();
router.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 review.save();
await campground.save();
res.redirect(`/campgrounds/${campground._id`);
}))
router.delete('/campgrounds/:id/reviews/:reviewId', catchAsync(async (req, res) => {
const { id, reviewId } = req.params;
await Campground.findByIdAndUpdate(id, { $pull: { reviews: reviewId } } );
await Review.findByIdAndDelete(reviewId);
res.redirect(`/campgrounds/${id}`);
}))
module.exports = router;
Configuring Session
session will be added to the main app.js file.
const sessionConfig = {
secret: 'secretcode',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}
app.use(session(sessionConfig))
Setting Up Flash
To display a quick message to the user that the data was successful. The message will disappear once the page has been reloaded/refreshed.
app.use(flash());
app.use((req, res, next) => {
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
})
Flash Success Partial
in the flash.ejs file
Top comments (0)