[英]How to get all the keys in a joi schema?
I had a joi schema like this我有一个这样的 joi 模式
const userModel = Joi.object({
id: Joi.string().min(3).max(50),
username: Joi.string().min(10).max(100)
... other 10 properties
})
the thing is I wanted to get the values of all the keys like问题是我想获取所有键的值,例如
["id","username",...]
I tried using Object.keys(userModel), but that is returning an unexpected value like我尝试使用 Object.keys(userModel),但这会返回一个意外的值,例如
[
"isJoi",
"_currentJoi",
"_type",
"_settings",
"_baseType",
"_valids",
"_invalids",
"_tests",
"_refs",
"_flags",
"_description",
"_unit",
"_notes",
"_tags",
"_examples",
"_meta",
"_inner"
]
Something like this could help.这样的事情可能会有所帮助。
const userModel = Joi.object({
id: Joi.string().min(3).max(50),
username: Joi.string().min(10).max(100)
})
const keys = [];
for (var i of userModel._ids._byKey.entries()){
keys.push(i[0])
}
console.log(keys);
The reason for the unexpected behaviour is due to the fact the userModel is not an ordinary object, it's a joi object.出现意外行为的原因是因为 userModel 不是普通的 object,而是 joi object。
A possible solution is to check the userModel._ids._byKey.keys()
to get a Map iterator of all of the keys in the schema.一种可能的解决方案是检查userModel._ids._byKey.keys()
以获取架构中所有键的 Map 迭代器。 The problem with this solution is that you count on the internals of the Joi framework.此解决方案的问题在于您依赖 Joi 框架的内部结构。
I might suggest another approach: Extract the required fields in a separate data structure - array or object and extend the Joi schema based on that.我可能会建议另一种方法:在单独的数据结构中提取所需的字段 - 数组或 object 并在此基础上扩展 Joi 模式。
I've just been struggling with this myself.我自己一直在为此苦苦挣扎。 After some digging in the api I found this在对 api 进行了一些挖掘之后,我发现了这个
For a Joi.object This returns a simple object with a property called keys对于 Joi.object 这将返回一个简单的 object 具有称为键的属性
{
type: 'object',
keys: {
nestedItem1: { type: 'any', rules: [Array], allow: [Array] },
nestedItem2: { type: 'string', flags: [Object], rules: [Array] },
}
}
It's pretty straightforward from there.从那里开始很简单。
const userModel = Joi.object({
id: Joi.string().min(3).max(50),
username: Joi.string().min(10).max(100)
});
const keys = Object.keys(userModel.describe().keys);
console.log(keys)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.