express-blog-api/controllers/user.js
2023-09-29 16:23:59 -07:00

118 lines
3.1 KiB
JavaScript

const asyncHandler = require("express-async-handler");
const bcrypt = require("bcryptjs");
const User = require("../models/user.js");
const { body, validationResult } = require("express-validator");
const { default: mongoose } = require("mongoose");
// C
exports.post = [
// Validate and sanitize username
body("username", "Please enter username!")
.isLength({ min: 1 })
.trim()
.escape(),
// Validate and sanitize password
body("password", "Please enter password!")
.isLength({ min: 1 })
.trim()
.escape(),
asyncHandler(async (req, res, next) => {
const errors = validationResult(req);
// if there are validation errors, return them
if (!errors.isEmpty()) {
return res.status(400).json({
message: "There were validation errors!",
errors: errors.array(),
});
}
const { username, password } = req.body; // get fields from body
const dbUser = await User.findOne({ username: req.params.username })
.lean()
.exec();
const exists = await User.findOne({ username: username }).lean().exec();
if (exists) {
return res.status(409).json({
message: "Username is taken!",
});
}
// else
const user = new User({
username: username,
password: await bcrypt.hash(password, 10),
});
await User.findByIdAndUpdate(dbUser._id, user, {});
return res.status(200).json({
message: "User created!",
});
}),
];
// R
exports.get = asyncHandler(async (req, res, next) => {
const user = await User.findOne({ username: req.params.username })
.lean()
.exec(); // gets user based on username
return res.status(200).json({
user,
});
});
// U
exports.put = [
// Validate and sanitize username
body("username", "Please enter username!")
.isLength({ min: 1 })
.trim()
.escape(),
// Validate and sanitize password
body("password", "Please enter password!")
.isLength({ min: 1 })
.trim()
.escape(),
asyncHandler(async (req, res, next) => {
// return any validation errors
const errors = validationResult(req);
// if there are validation errors, return them
if (!errors.isEmpty()) {
return res.status(400).json({
message: "Comment produced validation errors!",
errors: errors.array(),
});
}
// check for duplicates
const { username, password } = req.body; // get fields from body
const exists = await User.findOne({ username: originalUsername })
.lean()
.exec();
if (exists) {
return res.status(409).json({
message: "Username is taken!",
});
}
// otherwise update user
const user = new User({
username: username,
password: await bcrypt.hash(password, 10),
});
await user.save(); // make and save user
return res.status(200).json({
message: "User created!",
});
}),
];
// D
exports.delete = asyncHandler(async (req, res, next) => {
// if everything is correct, delete user
await User.findOneAndDelete({ username: originalUsername }).exec();
return res.status(200).json({ message: "Post deleted!" });
});