Untitled

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

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

const checkUsedId = async (userId: string): Promise<{ status: number; message: string }> => {
  switch (true) {
    case !userId:
      return { status: 400, message: '"userId" is required' };
    case typeof userId !== 'number':
      return { status: 422, message: '"userId" must be a number' };
    default:
      const productModelFindAll = await ProductModel.findAll({ attributes: ['userId'] });
      const userIdFromProduct = productModelFindAll.map((id) => id.dataValues.userId);
      return userIdFromProduct.includes(Number(userId)) 
      ? { status: 200, message: 'User ID is valid' } 
      : { status: 422, message: '"userId" not found' };
  }
};

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

const mware = async (req: Request, res: Response, next: NextFunction): Promise<Response | void> => {
  const { name, price, userId } = req.body;
  const nameValidation = checkName(name);
  switch (nameValidation.status) {
    case 200:
      break;
    default:
      return res.status(nameValidation.status).json({ message: nameValidation.message });
  }
  const userIdValidation = await checkUsedId(userId);
  switch (userIdValidation.status) {
    case 200:
      break;
    default:
      return res.status(userIdValidation.status).json({ message: userIdValidation.message });
  }
  const priceValidation = checkPrice(price);
  switch (priceValidation.status) {
    case 200:
      break;
    default:
      return res.status(priceValidation.status).json({ message: priceValidation.message });
  }
  next();
};

export default mware;
Editor is loading...
Leave a Comment