Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.2 kB
2
Indexable
Never
const joi = require('joi');
const impProdModel = require('../models/products');

const existingItem = async (id, res) => {
  const item = await impProdModel.getById(id);
  if (!item) {
    return res.status(404).json({ message: 'Product not found' });
  }
};

const validationSchema = joi.object({
  productId: joi.number().required(),
  quantity: joi.number().min(1).required(),
});

const schemaQuantity = joi.object({
  quantity: joi.number().min(1).required(),
});

const reqMiss = (error, res) => {
  const prodMessage = error.includes('"productId is required"');
  const quantMessage = error.includes('"quantity" is required');

  if (prodMessage || quantMessage) {
    return res.status(400).json({ message: error });
  }

  if (error.includes('"quantity" must be greater than or equal to 1')) {
    return res.status(422).json({ message: error });
  }
};

const itemValidation = async (item, res) => {
  const { error } = validationSchema.validate(item);

  if (error) {
    const invalidErrorMessage = error.details[0].message;
    const invalidResponseError = reqMiss(invalidErrorMessage, res);
    if (invalidResponseError) return invalidResponseError;
  }
  const responseItem = await existingItem(item.productId, res);
  if (responseItem) return responseItem;
};

const saleValidation = async (req, res, next) => {
  const soldItems = req.body;
  const sales = soldItems.map((item) => itemValidation(item, res));
  const response = await Promise.all(sales);
  const resError = response.find((item) => item);
  if (resError) return resError;
  next();
};

const quantityValidation = async (req, res, next) => {
  const { quantity } = req.body;
  const { error } = schemaQuantity.validate({ quantity });
  if (error) {
    const invalidResponseError = error.details[0].message;
    if (invalidResponseError.includes('"quantity" is required')) {
      return res.status(400).json({ message: invalidResponseError });
    }
    if (invalidResponseError.includes('"quantity" must be greater than or equal to 1')) {
      return res.status(422).json({ message: invalidResponseError });
    }
    return res.status(400).json({ message: invalidResponseError });
  }
  next();
};

module.exports = { saleValidation, quantityValidation };
Leave a Comment