Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
1.3 kB
1
Indexable
Never
// PRICE.MIDDLEWARE.TS

import { Request, Response, NextFunction } from 'express';
import ProductModel from '../database/models/product.model';

const firstPart = (req: Request, res: Response, next: NextFunction) => {
  const { price } = req.body;
  if (!price) {
    return res.status(400).json({ message: '"price" is required' });
  }

  if (typeof price !== 'string') {
    return res.status(422).json({ message: '"price" must be a string' });
  }

  if (price.length < 3) {
    return res.status(422).json({ message: '"price" length must be at least 3 characters long' });
  }

  next();
};

const userIdValidator = (req: Request, res: Response, next: NextFunction) => {
  const { userId } = req.body;

  if (!userId) {
    return res.status(400).json({ message: '"userId" is required' });
  }

  if (typeof userId !== 'number') {
    return res.status(422).json({ message: '"userId" must be a number' });
  }

  // Test if the user exists
  ProductModel.findAll({ attributes: ['userId'] }).then((item) => {
    const userIds = item.map((id) => id.dataValues.userId);
    if (!userIds.includes(userId)) {
      return res.status(422).json({ message: '"userId" not found' });
    }
  });

  next();
};

export default { firstPart, userIdValidator };
Leave a Comment