express-blog-api/controllers/post.js
2023-09-18 13:43:22 -07:00

124 lines
3.4 KiB
JavaScript

const { default: mongoose } = require("mongoose");
const asyncHandler = require("express-async-handler");
const { body, validationResult } = require("express-validator");
const Post = require("../models/post.js");
const Comment = require("../models/comment.js");
const passport = require("passport");
const jwtStrategy = require("../strategy/jwt.js");
passport.use(jwtStrategy);
// returns json object with ALL posts and comments
exports.index = asyncHandler(async (req, res, next) => {
const dbPosts = await Post.find().lean().exec();
const posts = [];
for (let i = 0; i < dbPosts.length; i++) {
const comments = await Comment.find({ post: dbPosts[i]._id });
const post = {
title: dbPosts[i].title,
date: dbPosts[i].date,
text: dbPosts[i].text,
author: dbPosts[i].author,
published: dbPosts[i].published,
_id: dbPosts[i]._id,
comments: comments,
};
posts.push(post);
}
return res.status(200).json({ posts });
});
// makes new post - C
(exports.post = passport.authenticate("jwt", { session: false })),
[
// Validate and sanitize title
body("title", "Please enter blog post title!")
.isLength({ min: 1 })
.trim()
.escape(),
// Validate and sanitize text
body("text", "Please enter blog post text!")
.isLength({ min: 1 })
.trim()
.escape(),
// Process request after authentication, validation and sanitization
asyncHandler(async (req, res, next) => {
const errors = validationResult(req);
// if there are validation errors, render with errors
if (!errors.isEmpty()) {
res.render("/admin/create"),
{
errors: errors.array(),
};
return;
}
// else data is valid, make post object
const post = new Post({
title: req.body.title,
date: new Date(),
text: req.body.text,
author: req.user.username,
_id: new mongoose.Types.ObjectId(),
});
// save to DB
await post.save();
return res.status(200).json({
message: "Post created!",
});
}),
];
// returns post in json format - R
exports.get = asyncHandler(async (req, res, next) => {
const post = await Post.findOne({ _id: req.params.postID }).lean().exec();
return res.status(200).json({ post });
});
// updates post - U
(exports.put = passport.authenticate("jwt", { session: false })),
[
// Validate and sanitize title
body("title", "Please enter blog post title!")
.isLength({ min: 1 })
.trim()
.escape(),
// Validate and sanitize text
body("text", "Please enter blog post text!")
.isLength({ min: 1 })
.trim()
.escape(),
// Process request after sanitization and validation
asyncHandler(async (req, res, next) => {
const dbPost = await Post.findOne({ _id: req.params.postID })
.lean()
.exec();
const post = {
title: req.body.title,
date: new Date(),
text: req.body.text,
author: dbPost.author,
published: dbPost.published,
_id: dbPost._id,
};
await post.save();
return res.status(200).json({
message: "Post updated!",
});
}),
];
// deletes a post - D
(exports.delete = passport.authenticate("jwt", { session: false })),
asyncHandler(async (req, res, next) => {
await Post.findByIdAndDelete({ _id: req.params.postID }).exec();
return res.status(200).json({ message: "Post deleted!" });
});