Untitled

 avatar
unknown
plain_text
a year ago
2.4 kB
1
Indexable
import { Request, Response, NextFunction } from 'express';
import ProductModel from '../database/models/product.model';

const checkName = (name:string): { status: number; message: string } => {
  if (!name || name === undefined) {
    return { status: 400, message: '"name" is required' };
  }  
  if (typeof name !== 'string') {
    return { status: 422, message: '"name" must be a string' };
  }
  if (name.length < 3) {
    return { status: 422, message: '"name" length must be at least 3 characters long' };
  }
  return { status: 200, message: 'Name is valid' };
};

const checkUsedId = async (userId: string): Promise<{ status: number; message: string }> => {
  if (!userId) {
    return { status: 400, message: '"userId" is required' };
  }
  if (typeof userId !== 'number') {
    return { status: 422, message: '"userId" must be a number' };
  }

  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: 200, message: 'User ID is valid' };
};

const checkPrice = (productPrice:string): { status: number; message: string } => {
  if (!productPrice || productPrice === undefined) {
    return { status: 400, message: '"price" is required' };
  }
  if (typeof productPrice !== 'string') {
    return { status: 422, message: '"price" must be a string' };
  }
  if (productPrice.length < 3) {
    return { status: 422, message: '"price" length must be at least 3 characters long' };
  }
  return { status: 200, message: 'Price is valid' };
};

const middleware = async (req: Request, res: Response, next: NextFunction)
:Promise<Response | void> => {
  const { name, price, userId } = req.body;

  const nameValidation = checkName(name);
  if (nameValidation.status !== 200) {
    return res.status(nameValidation.status).json({ message: nameValidation.message });
  }

  const userIdValidation = await checkUsedId(userId);
  if (userIdValidation.status !== 200) {
    return res.status(userIdValidation.status).json({ message: userIdValidation.message });
  }

  const priceValidation = checkPrice(price);
  if (priceValidation.status !== 200) {
    return res.status(priceValidation.status).json({ message: priceValidation.message });
  }

  next();
};

export default middleware;
Leave a Comment