【问题标题】:Get all fields in the Joi schema that are optjonal获取 Joi 模式中可选的所有字段
【发布时间】:2021-09-12 22:57:17
【问题描述】:

如何获取在 Joi 对象中设置为可选的字段名称的数组或列表?

例如:

export const schema = Joi.object<SomeType>({
  field1: Joi.string().required(),
  field2: Joi.string().guid(),
  field3: Joi.string().allow('').optional(),
  field4: Joi.string().allow('').optional(),
});

我应该能够检索到 field3、field4。

哈皮乔伊https://www.npmjs.com/package/@hapi/joi

【问题讨论】:

    标签: hapijs


    【解决方案1】:

    您可以使用describe 这样做:

    返回一个表示内部配置的对象 架构。对于调试和公开模式的配置很有用 其他系统,例如用户界面中的有效值。

    我们开始吧:

    for (const [key, value] of Object.entries(queueSchemaBase.describe().keys)) {
      if (value.flags?.presence === 'optional') {
        console.log(`${key} is optional`);
      }
    }
    

    输出:

    field3 is optional
    field4 is optional
    

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 1970-01-01
      • 2019-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 2017-03-29
      • 2016-09-14
      相关资源
      最近更新 更多