代码之家  ›  专栏  ›  技术社区  ›  Thomas

Joi嵌套模式和默认值

  •  4
  • Thomas  · 技术社区  · 7 年前

    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

    2 回复  |  直到 7 年前
        1
  •  9
  •   Vikash Rathee    5 年前

    更新日期: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();
    
        2
  •  7
  •   nerdlinger    6 年前

    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')