简体   繁体   English

Joi 模式验证:Joi.object 从数组中定义有效键

[英]Joi schema validation: Joi.object define valid keys from an array

I have a Joi schema like this:我有一个这样的 Joi 模式:

var schema = Joi.object().keys({ filter: Joi.object({ }) })

Then I have all valid keys for filter-object in a separate array called validKeys.然后我在一个名为 validKeys 的单独数组中拥有过滤对象的所有有效键。

I would like to reference validKeys with filter-object.我想用 filter-object 引用 validKeys。 Otherwise I would have to hard code the allowed values like this:否则我将不得不像这样硬编码允许的值:

var schema = Joi.object().keys({ filter: Joi.object({ allowed1:Joi.string(), allowed2: Joi.string(), ... }) }) 

which I don't want to do.我不想这样做。 Is this possible with Joi or some other Javascript tools?使用 Joi 或其他一些 Javascript 工具可以做到这一点吗?

I'm not really sure what your validkeys array looks like, but you if you set up your filter schema first and then your final schema, you can iterate through your keys and add them to your filter schema dynamically (assuming they're all supposed to be strings).我不确定您的validkeys数组是什么样的,但是如果您先设置过滤器架构,然后设置最终架构,您可以遍历您的键并将它们动态添加到您的过滤器架构中(假设它们都是假设的)成为字符串)。

const joi = require('joi');

// not sure what valid key structure is like..
const validkeys = ['allowed1', 'allowed2', 'allowed3'];

// set up filter schema first.
let filterschema = {};

for (let i = 0; i < validkeys.length; i++) {
    filterschema[validkeys[i]] = joi.string();
}

// set up the final schema
let finalschema = joi.object().keys({
    filter: filterschema
});

// test
let testobj = {
    filter: {
        allowed1: 'cuthbert',
        allowed2: 'susan',
        allowed5: 'jake' // should NOT be allowed.
    }
};

let result = joi.validate(testobj, finalschema);

// should fail because key allowed5 isn't defined in filter schema.
console.log(JSON.stringify(result, null, 2));

Here's how I do that:我是这样做的:

{
  filter: Joi.object().unknown(false).required().keys(['allowed1', 'allowed2', 'allowed3'].reduce((acc, val) => {
    acc[val] = Joi.any()

    return acc
  }, {}))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM