Как проверить массив объектов в теле запроса, используя JOI - PullRequest
0 голосов
/ 19 марта 2020

Я пытаюсь проверить тело запроса на размещенный заказ. Я получаю массив json объектов в теле запроса, который я пытаюсь проверить. Каждый раз, когда я получаю сообщение об ошибке "" productId "требуется"

Вот мое тело запроса:

req.body={
    "productId": [
        { "id": "5dd635c5618d29001747c01e", "quantity": 1 },
        { "id": "5dd63922618d29001747c028", "quantity": 2 },
        { "id": "5dd635c5618d29001747c01e", "quantity": 3 }
    ]
}

Вот функция valdateOrder для проверки тела запроса:

function validateOrder(req.body) {
    const schema = {

        productId: joi.array().items(
            joi.object().keys({
                id: joi.string().required(),
                quantity: joi.string().required()
            })).required(),
    }

    return joi.validate(req.body, schema)

}

Буду очень признателен, если кто-нибудь укажет, что не так с моей функцией validateOrder.

1 Ответ

1 голос
/ 19 марта 2020

Это кажется странным способом go об этом. Согласно https://hapi.dev/module/joi/, определите вашу схему как свою собственную, затем проверьте ваши данные , используя эту схему:

const Joi = require('@hapi/joi');

const schema = Joi.object({
  productId: Joi.array().items(
    Joi.object(
      id: Joi.string().required(),
      quantity: Joi.number().required()
    )
  )
};

module.exports = schema;

И затем вы подтвердите это в промежуточное ПО вашего маршрута:

const Joi = require('@hapi/joi');
const schema = require(`./your/schema.js`);

function validateBody(req, res, next) {
  // If validation passes, this is effectively `next()` and will call
  // the next middleware function in your middleware chain.

  // If it does not, this is efectively `next(some error object)`, and
  // ends up calling your error handling middleware instead. If you have any.

  next(schema.validate(req.body));
}

module.exports = validateBody;

которое вы используете, как и любое другое промежуточное ПО в express:

const validateBody = require(`./your/validate-body.js`);

// general error handler
app.use(function errorHandler(err, req, res, next) {
  if (err === an error you know comes form Joi) {
    // figure out what the best way to signal "your POST was bad"
    // is for your users
    res.status(400).send(...);
  }
  else if (...) {
    // ...
  }
  else {
    res.status(500).send(`error`);
  }
});

// post handler
app.post(`blah`, ..., ..., validateBody, ..., ..., (req, res) => {
  // final response
});
...