Node.JS - @hapi/joi - any.when() - 无法在 "then condition" 添加 .validate()

Node.JS - @hapi/joi - any.when() - not able to add .validate() at the "then condition"

我无法设置它按预期工作的 joi-schema...

这是我尝试做的事情:

这是代码,无法正常工作

let Joi = require("@hapi/joi");

const schema = Joi.object({
   internal: Joi.boolean(),
   role: 
     Joi.array()
      .items(Joi.string().trim())
      .required()

      // the when condition is not replacing properly
      .when('internal', {
        is: true,
        then: Joi.array()
          .items(Joi.string().valid("Admin"))
          .required()
  }),
});

console.log(schema.validate({role: ["Any Role"]})) // OK
console.log(schema.validate({internal: false, role: ["Any role allowed"]})) // OK

console.log(schema.validate({internal: true, role: ["WRONG"]})) // FAIL, should have thrown error

... 而替换数组函数本身工作正常:

const passingschema = Joi.object({
  role: Joi.array()
  .items(Joi.string().valid("Admin"))
  .required()
})

console.log(passingschema.validate({role: ["Admin"]})) // OK
console.log(passingschema.validate({role: ["WRONG"]})) // OK - throws error as expected
});

请告诉我,一旦内部设置为 true,如何相应地替换角色验证。

也许可以在文档中尝试 is: valid(true).required(),它说您需要 is 上的 required() 才能完成这项工作。

根据这个link,这是解决方案:

Joi.array().required()
   .when('internal', {
       is: true,
       then: Joi.array().items(Joi.string().valid("Admin")),
       otherwise: Joi.array().items(Joi.string())
   })