๐์ฝ๋ ๋ณด๋ฌ๊ฐ๊ธฐ
https://github.com/Sara-Jo/BeWild/tree/ff6af5992138786a4eb34dc1eb9558136edae3ba
const Joi = require("joi");
module.exports.campgroundSchema = Joi.object({
campground: Joi.object({
title: Joi.string().required(),
price: Joi.number().required().min(0),
image: Joi.string().required(),
location: Joi.string().required(),
description: Joi.string().required()
}).required()
});
class ExpressError extends Error {
constructor(message, statusCode){
super();
this.message = message;
this.statusCode = statusCode;
}
}
module.exports = ExpressError;
module.exports = func => {
return (req, res, next) => {
func(req, res, next).catch(next);
}
}
const { campgroundSchema } = require("./schemas.js");
const catchAsync = require("./utils/catchAsync");
const ExpressError = require("./utils/ExpressError");
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();
}
}
/* Routes */
app.get("/", (req, res) => {
res.render("home");
});
// Read
app.get("/campgrounds", **catchAsync**(async (req, res) => {
const campgrounds = await Campground.find({});
res.render("campgrounds/campgrounds", { campgrounds });
}));
app.get("/campgrounds/new", (req, res) => {
res.render("campgrounds/new");
});
// Create
app.post("/campgrounds", **validateCampground, catchAsync**(async(req, res) => {
const campground = new Campground(req.body.campground);
await campground.save();
res.redirect(`/campgrounds/${campground._id}`);
}));
app.get("/campgrounds/:id", **catchAsync**(async(req, res) => {
const campground = await Campground.findById(req.params.id);
res.render("campgrounds/show", { campground });
}));
app.get("/campgrounds/:id/edit", **catchAsync**(async(req, res) => {
const campground = await Campground.findById(req.params.id);
res.render("campgrounds/edit", { campground });
}));
// Update
app.put("/campgrounds/:id", **validateCampground, catchAsync**(async(req, res) => {
const {id} = req.params;
const campground = await Campground.findByIdAndUpdate(id, {...req.body.campground});
res.redirect(`/campgrounds/${campground._id}`);
}));
// Delete
app.delete("/campgrounds/:id", **catchAsync**(async(req, res) => {
const {id} = req.params;
await Campground.findByIdAndDelete(id);
res.redirect("/campgrounds");
}));
app.all("*", (req, res, next) => {
next(new **ExpressError**("Page Not Found", 404));
});
app.use((err, req, res, next) => {
const {statusCode = 500} = err;
if(!err.message) err.message = "Oh No, Something Went Wrong!";
res.status(statusCode).render("error", {err});
});
app.listen(3000, () => {
console.log("Serving on port 3000.");
});