Untitled

 avatar
unknown
plain_text
a year ago
1.3 kB
4
Indexable
// 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 };
Editor is loading...
Leave a Comment