joh*_*thy 4 javascript validation node.js joi
我正在构建一个 Node/Express API 并使用 Joi 进行验证。这是一个很棒的软件包,并且非常有用。然而,我们已经厌倦了做这样的事情:
const mySchema = joi.object({
thing1: joi.string().required(),
thing2: joi.string().required(),
thing3: joi.string().required(),
thing4: joi.string().required(),
thing5: joi.string().required(),
}).required();
Run Code Online (Sandbox Code Playgroud)
我们希望默认情况下所有内容都是必需的,并手动调用.optional
以覆盖它。事实上,这似乎是一个明智的默认设置——但暂时将其搁置一旁。
有没有办法实现这一目标?
您可以使用precence
选项使字段默认为必填项。例子:
const mySchema = joi.object({
thing1: joi.string(),
thing2: joi.string(),
thing3: joi.string(),
thing4: joi.string(),
thing5: joi.string(),
}).options({presence: 'required'});
Run Code Online (Sandbox Code Playgroud)
不存在制作所需每个密钥的标准方法,但有一些解决方法。
解决方法之一是使用.requiredKeys()
and .optionalKeys()
onJoi.object()
看一下.describe()
函数,
它返回一个具有键的对象flags
。
当一个键被标记为“可选”时,我们得到flags.presence = 'optional'
使用该信息,您可以调用.describe()
每个键并准备两个requiredKey
数组optionalKeys
然后,您可以分别将这些数组传递给.requiredKeys()
和.optionalKeys()
。
例如:
假设您将 joi 模式定义为:
const joiSchemaKeys = {
thing1: Joi.string(),
thing2: Joi.string().optional(),
thing3: Joi.string(),
thing4: Joi.string(),
thing5: Joi.string().required()
};
Run Code Online (Sandbox Code Playgroud)
然后,您可以准备两个数组optionalKeys
并requiredKeys
使用:
const initialKeyInformation = {
requiredKeys: [],
optionalKeys: []
};
const prepareKeysInformation = keys =>
Object.keys(keys).reduce((accumulated, aKey) => {
const description = keys[aKey].describe();
const isMarkedOptional =
description.flags &&
description.flags.presence &&
description.flags.presence === "optional";
if (isMarkedOptional) {
console.log(`"${aKey}" is marked optional`);
accumulated.optionalKeys.push(aKey);
} else {
console.log(`"${aKey}" is not marked, making it required`);
accumulated.requiredKeys.push(aKey);
}
return accumulated;
}, initialKeyInformation);
const { optionalKeys, requiredKeys } = prepareKeysInformation(joiSchemaKeys);
Run Code Online (Sandbox Code Playgroud)
完成后,您可以准备 joi 模式,如下所示:
const schema = Joi.object()
.keys(joiSchemaKeys)
.requiredKeys(requiredKeys)
.optionalKeys(optionalKeys);
Run Code Online (Sandbox Code Playgroud)
这样,除非另有说明,否则您将获得所需的每个密钥。