[英]What's the difference between Joi.object().keys() and append() methods in terms of adding more keys
I have this piece of code我有这段代码
const baseSchema = Joi.object.keys({
name: Joi.string().required()
})
Now I want to add more keys to this schema, I can write现在我想为这个模式添加更多的键,我可以写
const basicInfoSchema = baseSchema.keys({
address: Joi.string().required(),
phoneNumber: Joi.number().required()
})
or或者
const basicInfoSchema = baseSchema.append({
address: Joi.string().required(),
phoneNumber: Joi.number().required()
})
What's the difference between the two?两者有什么区别?
append
has a generic parameter to give some typing to the expected object. append
有一个通用参数,可以为预期的 object 提供一些类型。 Like Joi.object<>()
does.就像
Joi.object<>()
一样。 keys
has no generic parameter. keys
没有通用参数。
Also looking at the source code bellow (version 17.6.0), you can see append calls keys
under the hood.还查看下面的源代码(版本 17.6.0),您可以看到 append 调用引擎盖下的
keys
。 I won't paste the documentation, but you can read it there https://joi.dev/api/?v=17.6.0 .我不会粘贴文档,但您可以在那里阅读https://joi.dev/api/?v=17.6.0 。
Basically, append
only do the else
clause of keys
method.基本上,
append
只做keys
方法的else
子句。 While keys
can also "Allow all" (any key allowed) or "Allow none" (no keys allowed) of the existing keys.而
keys
也可以“允许所有”(允许任何键)或“不允许任何键”(不允许任何键)现有键。 keys
has two extra functionalities. keys
有两个额外的功能。
append: {
method(schema) {
if (schema === null ||
schema === undefined ||
Object.keys(schema).length === 0) {
return this;
}
return this.keys(schema);
}
},
keys: {
method(schema) {
Assert(schema === undefined || typeof schema === 'object', 'Object schema must be a valid object');
Assert(!Common.isSchema(schema), 'Object schema cannot be a joi schema');
const obj = this.clone();
if (!schema) { // Allow all
obj.$_terms.keys = null;
}
else if (!Object.keys(schema).length) { // Allow none
obj.$_terms.keys = new internals.Keys();
}
else {
obj.$_terms.keys = obj.$_terms.keys ? obj.$_terms.keys.filter((child) => !schema.hasOwnProperty(child.key)) : new internals.Keys();
for (const key in schema) {
Common.tryWithPath(() => obj.$_terms.keys.push({ key, schema: this.$_compile(schema[key]) }), key);
}
}
return obj.$_mutateRebuild();
}
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.