我有一个对象数组,这些对象代表端点输入的有效组合:
const portfolios = [
{ "name": "portfolioA", "product": "productA" },
{ "name": "portfolioB", "product": "productB" },
{ "name": "portfolioB", "product": "productC" },
{ "name": "portfolioC", "product": "productD" },
...
]
例如,用户可以使用“ productA”请求“ portfolioA”,但不能使用“ productB”,或者可以使用“ productB”或“ productC”请求“ portfolioB”。
我将获得的输入如下所示:
portfolio: {
name: "portfolioA",
product: "productA"
}
我希望能够以编程方式对照“投资组合”中的有效对象检查该对象。我以为可以使用
Joi.object().valid(portfolios)
完成此操作,但验证失败。我可以使用when()来使用下面的模式手动检查每一个,但是投资组合的数组可以更改,我宁愿不必每次都更改验证代码。我宁愿只给它一个有效的对象数组。
portfolio: {
name: Joi.string().required(),
product: Joi.string().required()
.when('name', { is: Joi.string().valid('portfolioA'), then: Joi.string().valid('productA') })
.when('name', { is: Joi.string().valid('portfolioB'), then: Joi.string().valid(['productB', 'productC']) })
}
附带说明一下,当验证失败时,我会看到它而不是字符串表示形式。
\"portfolio\" must be one of [[object Object], [object Object], [object Object], [object Object], [object Object]
有没有办法用Joi对照一组对象检查对象?
最佳答案
我想出了怎么做。 Joi 9.0.0-0包含一个名为extends
的新方法,可以为我解决此问题。
const portfolios = { ... }
const customJoi = Joi.extend({
base: Joi.object(),
name: 'portfolio',
language: {
isValid: `portfolio must be one of ${JSON.stringify(portfolios)}`
},
rules: [
{
name: 'isValid',
validate(params, value, state, options) {
const found = results.find(e => e.name === value.name && e.product === value.product);
if (!found) {
return this.createError('portfolio.isValid', { v: value, q: params.q }, state, options);
}
return found;
}
}
]
});
然后在我的验证声明中,我可以使用
portfolio: customJoi.portfolio().isValid().required(),