Joi:如何只验证两个键中的一个(带数组)?

Joi: how to validate only one of two keys (with array)?

假设我有 user 个带有 id 个数字和 roles 个数组的对象:

const user = {
  id: 1,
  roles: [ 'admin' ]
};

如果满足以下条件,则此对象的验证应该通过:

  1. id 匹配一些外部值
  2. OR roles 包括 admin 字符串

我试过这种方法,但效果不如预期:

const schema = Joi.object({
  id: Joi.number().valid(Joi.ref('$userId')), // shouldn't pass as $userId === 2
  roles: Joi.array().has(Joi.string().valid('admin')) // should pass as user has 'admin' role
}).or('id');

schema.validate(user, {
  context: {
    userId: 2
  }
}); // should pass as `user` includes `admin` in `roles` (but `userId` not equals `user.id`)

我找到了答案,这个场景可以使用when操作来完成:

Joi.object({
  id: Joi.number(),
  roles: Joi.array().when('id', { 
    not: Joi.ref('$userId'), 
    then: Joi.array().has(Joi.string().valid('admin'))
  })
});