我有这样的Joi架构:
var schema = Joi.object().keys({ filter: Joi.object({ }) })
然后我在一个名为validKeys的单独数组中拥有filter-object的所有有效键。
我想用filter-object引用validKeys。否则,我将不得不硬编码允许的值,如下所示:
var schema = Joi.object().keys({ filter: Joi.object({ allowed1:Joi.string(), allowed2: Joi.string(), ... }) })
我不想这样做。这可能与Joi或其他一些Javascript工具有关吗?
答案 0 :(得分:0)
我不确定您的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));