如何修改 Joi 中的现有键 Object

How to Modify Existing Keys in Joi Object

Joi 验证不支持修改现有 object 个键。

我正在对 parent 和 child 类 使用 Joi 验证。 parent 的验证是所有 children 的基本验证,但每个 child 都有特定的限制或附加字段。 我希望能够使用我的 parent Joi object 并能够修改现有密钥以适应某些限制。

//Declare base class with an array at most 10 elements
const parent = {
    myArray: Joi.array().max(10)
}
//Now declare child with minimum 1 array value
const child = parent.append({
    foo: Joi.string(),
    myArray: Joi.array().min(1).required()
})

以上代码按预期工作 - 这意味着 child object 不会将 .limit(10) 限制应用于 parent。 但是,我想要它做到这一点。我确定 append 不是在这里使用的正确函数,但我不确定如何执行此操作。 我希望生成的 child 验证看起来像:

const child = {
    foo: Joi.string(),
    myArray: Joi.array().max(10).min(1).required()
}

你试过了吗:

const child = parent.append({
    foo: Joi.string(),
    myArray: parent.myArray.min(1).required()
});

刚试过:

const Joi = require('joi');

const parent = {
  x: Joi.array().max(10).required()
};

const child = Object.assign({}, parent, {
  x: parent.x.min(1).required(),
  y: Joi.string()
});

Joi.validate({
  x: [],
  y: 'abc'
}, child); // fails as .min(1) not satisfied

Joi.validate({
  x: [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
  y: 'abc'
}, child); // fails as .max(10) not satisfied

Joi.validate({
  x: [1],
  y: 'abc'
}, child); // OK

尝试在 Node v8.10.0 上使用新的 npm i joi(包装说明:"joi": "^14.3.1")。又或者您给出的示例太过琐碎,无法反映您的真实场景?