Joi Validation:有没有办法一次性允许多个模式对象的未知键

Joi Validation: Is there a way to allow unknown keys for several schema objects in one go

我有几个包含将近一百个模式对象的验证器文件。我想同时验证所有未知密钥。我已经想出了一种方法来验证我在下面发布的一个对象的未知键。有没有办法一次性完成所有工作?我正在寻找一种干燥的方法来做到这一点。

const schema = Joi.object().keys({
  a: Joi.string().required(),
  b: Joi.string().required()
}).unknown(true);

// or
const schema = Joi.object().keys({
  a: Joi.string().required(),
  b: Joi.string().required()
}).options({ allowUnknown: true })

您可以使用 .defaults 创建您自己的自定义 joi,在这种情况下,默认情况下会将 allowUnkown 设置为 true:

// Create your custom Joi
const customJoi = Joi.defaults((schema) => schema.options({
  allowUnknown: true 
}));

// schema using original Joi
const schema1 = Joi.object().keys({
  a: Joi.string().required(),
  b: Joi.string().required()
})

// schema using custom Joi
const schema2 = customJoi.object().keys({
  a: Joi.string().required(),
  b: Joi.string().required()
})
 
// INVALID, "c" is not allowd
schema1.validate({ a: "a", b: "b", c: 10 })
// VALID
schema2.validate({ a: "a", b: "b", c: 10 })

这也有效:

var Joi = require("joi").defaults((schema) => schema.options({
  allowUnknown: true 
}));

var Joi = require("joi")
Joi = Joi.defaults((schema) => schema.options({
  allowUnknown: true 
}));