Untitled
unknown
plain_text
2 years ago
1.7 kB
8
Indexable
const joi = require('joi');
const productsModel = require('../models/productsModel');
const productSchema = joi.object({
productId: joi.number().required(),
quantity: joi.number().min(1).required(),
});
const validarProductId = (item) => {
if (!item.productId) {
return { status: 400, mensagem: '{"message": "productId is required"}' };
}
return null;
};
const validarQuantity = (item) => {
if (!item.quantity || item.quantity <= 0) {
return { status: 422, mensagem: '{"message": "quantity must be greater than or equal to 1"}' };
}
return null;
};
const verificaProdutoExiste = async (productId) => {
const product = await productsModel.buscaId(productId);
return !!product;
};
const validarItemVenda = async (item) => {
const erros = [];
const { error } = productSchema.validate(item);
if (error) {
erros.push({ status: 400, mensagem: error.details[0].message });
}
const erroProductId = validarProductId(item);
if (erroProductId) {
erros.push(erroProductId);
}
const erroQuantity = validarQuantity(item);
if (erroQuantity) {
erros.push(erroQuantity);
}
const existeProduto = await verificaProdutoExiste(item.productId);
if (!existeProduto) {
erros.push({ status: 404, mensagem: '{"message": "Product not found"}' });
}
return erros;
};
const validarVenda = async (itensVenda) => {
const errosPromises = itensVenda.map(validarItemVenda);
const errosResultados = await Promise.all(errosPromises);
const errosTotais = errosResultados.filter((errosItem) => errosItem.length > 0);
return errosTotais.flat();
};
module.exports = { productSchema,
validarProductId,
validarQuantity,
verificaProdutoExiste,
validarVenda };Editor is loading...
Leave a Comment