Joi 嵌套模式和默认值
Joi nested schemas and default values
我正在尝试让 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
默认值。我一直在浏览文档,但似乎找不到任何关于此的信息,尽管我可能遗漏了一些明显的东西。有什么建议吗?
应该这样做:
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')
更新:2020 年 4 月。
现在,您可以在嵌套对象中使用 default()
。这是 commit in repo with test.
var schema = Joi.object({
a: Joi.number().default(42),
b: Joi.object({
c: Joi.boolean().default(true),
d: Joi.string()
}).default()
}).default();
我正在尝试让 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
默认值。我一直在浏览文档,但似乎找不到任何关于此的信息,尽管我可能遗漏了一些明显的东西。有什么建议吗?
应该这样做:
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')
更新:2020 年 4 月。
现在,您可以在嵌套对象中使用 default()
。这是 commit in repo with test.
var schema = Joi.object({
a: Joi.number().default(42),
b: Joi.object({
c: Joi.boolean().default(true),
d: Joi.string()
}).default()
}).default();