feat(validation): replace fieldValidation with express-validator on products and tags
Add products.validators.js and tags.validators.js following the same pattern as articles/users. Wire createProductRules, updateProductRules, and createTagRules into their respective routes via the validate middleware. Remove the local fieldValidation helper from both controllers and fix missing return statements on next() calls in products.controller.js.
This commit is contained in:
@@ -134,14 +134,10 @@ module.exports.getProduct = asyncHandler(async (req, res, next) => {
|
||||
module.exports.createProduct = asyncHandler(async (req, res, next) => {
|
||||
const { loggedUser } = req;
|
||||
|
||||
fieldValidation(req.body.product.title, next);
|
||||
fieldValidation(req.body.product.description, next);
|
||||
fieldValidation(req.body.product.body, next);
|
||||
|
||||
const { title, description, body, tagList } = req.body.product;
|
||||
const slugInDB = await Product.findOne({ where: { slug: slug(`${title}`) } });
|
||||
if (slugInDB) {
|
||||
next(new ErrorResponse("Title already exists", 400));
|
||||
return next(new ErrorResponse("Title already exists", 400));
|
||||
}
|
||||
|
||||
const product = await Product.create({
|
||||
@@ -181,7 +177,7 @@ module.exports.deleteProduct = asyncHandler(async (req, res, next) => {
|
||||
});
|
||||
|
||||
if (!product) {
|
||||
next(new ErrorResponse("Product not found", 404));
|
||||
return next(new ErrorResponse("Product not found", 404));
|
||||
}
|
||||
|
||||
if (product.authorId !== loggedUser.id) {
|
||||
@@ -203,7 +199,7 @@ module.exports.updateProduct = asyncHandler(async (req, res, next) => {
|
||||
});
|
||||
|
||||
if (!product) {
|
||||
next(new ErrorResponse("Product not found", 404));
|
||||
return next(new ErrorResponse("Product not found", 404));
|
||||
}
|
||||
if (product.authorId !== loggedUser.id) {
|
||||
return next(new ErrorResponse("Unauthorized", 401, "Authentication required."));
|
||||
@@ -277,8 +273,3 @@ module.exports.deleteFavoriteProduct = asyncHandler(async (req, res, next) => {
|
||||
res.status(200).json({ product });
|
||||
});
|
||||
|
||||
const fieldValidation = (field, next) => {
|
||||
if (!field) {
|
||||
return next(new ErrorResponse(`Missing fields`, 400));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -4,8 +4,6 @@ const ErrorResponse = require("../utils/errorResponse");
|
||||
|
||||
module.exports.createTag = asyncHandler(async (req, res, next) => {
|
||||
try {
|
||||
|
||||
fieldValidation(req.body.tag.name, next);
|
||||
const { name } = req.body.tag;
|
||||
const tagInDB = await TagService.tagIsInDB(name);
|
||||
if (tagInDB) {
|
||||
@@ -60,8 +58,3 @@ module.exports.getAllTags = asyncHandler(async (req, res, next) => {
|
||||
}
|
||||
});
|
||||
|
||||
const fieldValidation = (field, next) => {
|
||||
if (!field) {
|
||||
return next(new ErrorResponse(`Missing fields`, 400));
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user