使用 when 的简单 joi 模式不起作用

Simple joi schema using when does not work

我希望打印以下错误:

var joi = require('joi');

var schema = {
  role_type: joi.string(),
  info: {
    address: joi.object({
      postal_code: joi.string(),
      country: joi.string().uppercase().length(2)
    })
      .when('role_type', {
        is: 'org', // When role_type is "org" the address props become required
        then: {
          postal_code: joi.required(),
          country: joi.required()
        }
      })
  }
};

var data = {
  role_type: 'org',
  info: {address: {country: 'AF'}}
};

joi.assert(data, schema);

不幸的是,上面的代码没有产生任何错误。为什么?

在 joi v6 和最新的 v10 上测试。

结果是一个can't reference父对象数据:

References cannot point up the object tree, only to sibling keys, but they can point to their siblings' children

最简单的解决方法是将 .when() 向上移动一层,这样 joi 就会(深度)合并两个 info 子模式

var schema = {
  role_type: joi.string(),
  info: joi.object({
    address: joi.object({
      postal_code: joi.string(),
      country: joi.string().uppercase().length(2)
    })
  })
    .when('role_type', {
      is: 'org',
      then: joi.object({
        address: joi.object({
          postal_code: joi.required(),
          country: joi.required()
        })
      })
    })
};