【问题标题】:Joi - make everything required by default?Joi - 默认情况下需要的所有东西?
【发布时间】:2019-09-20 19:36:54
【问题描述】:

我正在构建一个 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();

我们希望 everything 在默认情况下是必需的,并手动调用 .optional 来覆盖它。事实上,这似乎是一个合理的默认设置——但暂时先不管它。

有没有办法做到这一点?

【问题讨论】:

  • 为什么不围绕这个构建一个包装函数呢?
  • @madalinivascu 因为它似乎可以通过验证库开箱即用地实现......

标签: javascript node.js validation joi


【解决方案1】:

您可以使用presence 选项使字段默认为必填项。示例:

const mySchema = joi.object({
    thing1: joi.string(),
    thing2: joi.string(),
    thing3: joi.string(),
    thing4: joi.string(),
    thing5: joi.string(),
}).options({ presence: 'required' });

【讨论】:

    【解决方案2】:

    不存在使每个密钥都成为必需的标准方法,但有一些变通方法。
    一种解决方法是在Joi.object() 上使用.requiredKeys().optionalKeys()

    看看.describe()函数,
    它返回一个具有键 flags 的对象。
    当一个键被标记为“可选”时,我们得到flags.presence = 'optional'

    使用该信息,您可以在每个键上调用 .describe() 并准备两个数组 requiredKeyoptionalKeys

    然后,您可以将这些数组分别传递给.requiredKeys().optionalKeys()

    例如:
    假设您将 joi 模式定义为:

    const joiSchemaKeys = {
        thing1: Joi.string(),
        thing2: Joi.string().optional(),
        thing3: Joi.string(),
        thing4: Joi.string(),
        thing5: Joi.string().required()
    };
    

    然后您可以使用以下方法准备两个数组 optionalKeysrequiredKeys

    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);
    

    完成后,您可以准备 joi 架构,如下所示:

    const schema = Joi.object()
        .keys(joiSchemaKeys)
        .requiredKeys(requiredKeys)
        .optionalKeys(optionalKeys);
    

    因此,除非另有说明,否则您将需要每个键。

    【讨论】:

      猜你喜欢
      • 2017-04-12
      • 2014-02-25
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2022-01-22
      • 2016-04-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多