如何使用joi中间件做OR语句和处理错误?

How to do OR statements and handling the errors with joi middleware?

今天我发现了一个非常有趣的中间件,用于通过 HTTP 请求验证正文。我说的是 Joi。但是我需要做一个 OR 语句来验证一个字段。

我的代码:

const { celebrate, Joi } = require('celebrate');
const joiObjectId = require('joi-objectid');
const constants = require('../../constants.js');

Joi.objectId = joiObjectId(Joi);

const validateBodySchema = celebrate({
  body: Joi.object().keys({
    name: Joi.string()
      .required()
      //.error(new Error('Name is a required field!'))
      .min(constants.MIN_CHAR_NAME)
      .max(constants.MAX_CHAR_NAME),
  
    address: Joi.string()
      .required()
      //.uri() -> This doesn't work because it checks whether the string is an uri valid AND an ip address. I need an OR here
      //.ip(),
    type: Joi.string()
      .required(),
  })
});

module.exports =  validateBodySchema;

在此之后,我在 app.js 的 post 方法中调用它。它上面写的方式“有效”。但是它抛出的错误很难读懂。

我的问题 是地址必须是 URL IP (ipv4) 地址。我这样做的方式是错误的,因为那是 and。有办法吗?

另一个问题是错误处理。如果我取消注释 .error(new Error('...')) 它会抛出一个错误说 AssertionError [ERR_ASSERTION]: value must be a joi 验证错误。在互联网上我还没有找到解决方案。你怎么看?有没有办法做到这一点,或者我只需要“经典”地做到这一点?

非常感谢!

我找到解决办法了! 从 https://joi.dev/api/?v=17.3.0#alternativestryschemas 你可以找到如何这样做:

address: Joi.alternatives().try(Joi.string().uri(),Joi.string().ip)

您可以验证两个选项,而不是检查地址是否为字符串:如果它是一个字符串并且它是一个 uri 或者它是否是一个字符串并且它是一个 ipv4。