【问题标题】:Joi nested schemas and default valuesJoi 嵌套模式和默认值
【发布时间】:2018-02-20 13:03:46
【问题描述】:

我试图让 Joi 在另一个引用的辅助模式上强制执行默认值。我有两个这样的模式:

const schemaA = Joi.object().keys({
  title: Joi.string().default(''),
  time: Joi.number().min(1).default(5000)
})

const schemaB = Joi.object().keys({
  enabled: Joi.bool().default(false),
  a: schemaA
})

我想要的是提供一个未定义 a 的对象,并让 Joi 为其应用默认值,如下所示:

const input = {enabled: true}

const {value} = schemaB.validate(input)

//Expect value to equal this:
const expected = {
  enabled: true,
  a: {
    title: '',
    time: 5000
  }
}

问题在于,由于密钥是可选的,因此根本不强制执行。所以我想要的是它是可选的,但如果不存在,则正确填充schemaA 默认值。我一直在查看文档,但似乎找不到任何关于此的信息,尽管我可能遗漏了一些明显的东西。有什么建议吗?

【问题讨论】:

    标签: javascript joi


    【解决方案1】:

    应该这样做:

    const schemaA = Joi.object().keys({
      title: Joi.string().default(''),
      time: Joi.number().min(1).default(5000),
    });
    
    const schemaB = Joi.object().keys({
      enabled: Joi.bool().default(false),
      a: schemaA.default(schemaA.validate({}).value),
    });
    

    虽然如果他们实现一个功能来让我们传入Joi 模式对象作为默认值会更好,例如:schemaA.default(schemaA)schemaA.default('object')

    【讨论】:

      【解决方案2】:

      更新:2020 年 4 月。

      现在,您可以在嵌套对象中使用default()。这是带有测试的commit in repo

      var schema = Joi.object({
                      a: Joi.number().default(42),
                      b: Joi.object({
                          c: Joi.boolean().default(true),
                          d: Joi.string()
                      }).default()
                  }).default();
      

      【讨论】:

      • 太好了,应该是这个问题的最佳答案。
      • 感谢更新。我不再使用 Joi,但我会为其他人标记它。
      猜你喜欢
      • 2016-08-12
      • 2020-02-14
      • 2018-10-11
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      相关资源
      最近更新 更多