Estoy tratando de verificar si los products enviados por el cliente son una matriz y no están vacíos usando un validador personalizado en express-validator.
Sin embargo, cuando envío el json correcto, sigo recibiendo un error que se ve así:
error devuelto por la API:
{ "error": [ { "value": [ { "productId": "548fefewrTNH563", "quantity": 3 }, { "productId": "548fefewrT4354563", "quantity": 2 } ], "msg": "Invalid value", "param": "products", "location": "body" } ] } El json enviado en la solicitud POST
{ "userId" : "61923f2df64756f1df629a7c", "products" : [ { "productId" : "548fefewrTNH563", "quantity" : 3 }, { "productId" : "548fefewrT4354563", "quantity" : 2 } ], "amount" : "2", "address" : "dfjkdj3djfnjj4jndfn" }Código en el archivo del validador:
const {check , validationResult} = require('express-validator'); exports.validateCreateOrder = [ check("userId", "UserId is missing").not().isEmpty(), check("products").custom(products=>{ if(!Array.isArray(products))throw new Error('Products need to be an array') if (products.length == 0 ) throw new Error ('Product array cant be empty') }), check("amount", "Amount is missing").not().isEmpty(), check("address", "Address is missing").not().isEmpty(), (req, res, next) => { const errors = validationResult(req); if (!errors.isEmpty()) return res.status(400).json({ error: errors.array() }); next(); },]