Untitled
unknown
plain_text
8 months ago
2.4 kB
3
Indexable
Never
import { Request, Response, NextFunction } from 'express'; import ProductModel from '../database/models/product.model'; const isNameValid = (name:string) : { status: number; message: string } => { if (name.length < 3) { return { status: 422, message: '"name" length must be at least 3 characters long' }; } if (!name || name === undefined) { return { status: 400, message: '"name" is required' }; } if (typeof name !== 'string') { return { status: 422, message: '"name" must be a string' }; } return { status: 0, message: 'No return' }; }; const isUserIdValid = async (userId: string) : Promise<{ status: number; message: string }> => { if (typeof userId !== 'number') { return { status: 422, message: '"userId" must be a number' }; } if (!userId) { return { status: 400, message: '"userId" is required' }; } const productModelFindAll = await ProductModel.findAll({ attributes: ['userId'] }); const userIdFromProduct = productModelFindAll.map((id) => id.dataValues.userId); if (!userIdFromProduct.includes(userId)) { return { status: 422, message: '"userId" not found' }; } return { status: 0, message: 'No return' }; }; const isPriceValid = (productPrice:string) : { status: number; message: string } => { if (typeof productPrice !== 'string') { return { status: 422, message: '"price" must be a string' }; } if (!productPrice || productPrice === undefined) { return { status: 400, message: '"price" is required' }; } if (productPrice.length < 3) { return { status: 422, message: '"price" length must be at least 3 characters long' }; } return { status: 0, message: 'No return' }; }; const productMiddleware = async (req: Request, res: Response, next: NextFunction) : Promise<Response | void> => { const { name, price, userId } = req.body; const validName = isNameValid(name); if (validName.status !== 0) { return res.status(validName.status) .json({ message: validName.message }); } const validUserId = await isUserIdValid(userId); if (validUserId.status !== 0) { return res.status(validUserId.status) .json({ message: validUserId.message }); } const validPrice = isPriceValid(price); if (validPrice.status !== 0) { return res.status(validPrice.status) .json({ message: validPrice.message }); } next(); }; export default productMiddleware;
Leave a Comment