59 lines
1.7 KiB
JavaScript
59 lines
1.7 KiB
JavaScript
const { default: mongoose } = require("mongoose");
|
|
const asyncHandler = require("express-async-handler");
|
|
const { body, validationResult } = require("express-validator");
|
|
|
|
const Comment = require("../models/comment.js");
|
|
|
|
// makes new comment - C
|
|
exports.post = [
|
|
// Validate and sanitize text
|
|
body("text", "Please enter comment!").isLength({ min: 1 }).trim().escape(),
|
|
|
|
// Validate and sanitize text
|
|
body("author", "Please enter comment author!")
|
|
.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()) {
|
|
return res.status(400).json({
|
|
message: "Comment produced validation errors!",
|
|
errors: errors.array(),
|
|
});
|
|
}
|
|
|
|
// else data is valid, make post object
|
|
const comment = new Comment({
|
|
date: new Date(),
|
|
text: req.body.text,
|
|
author: req.body.author,
|
|
post: req.params.postID,
|
|
_id: new mongoose.Types.ObjectId(),
|
|
});
|
|
|
|
// save to DB
|
|
await comment.save();
|
|
|
|
return res.status(200).json({
|
|
message: "Comment uploaded!",
|
|
});
|
|
}),
|
|
];
|
|
|
|
// returns comment in json format - R
|
|
exports.get = asyncHandler(async (req, res, next) => {
|
|
const comment = await Comment.findOneById(req.params.commentID).lean().exec();
|
|
return res.status(200).json({ comment });
|
|
});
|
|
|
|
// no U(pdate)
|
|
// comments cannot be edited as they can be made by anyone
|
|
// best to prevent impersonation
|
|
|
|
// no D(elete)
|
|
// again, would require authorization that is out of scope for this project
|