【问题标题】:AJV if-then-else conditional type based on enum基于枚举的 AJV if-then-else 条件类型
【发布时间】:2020-08-31 16:29:00
【问题描述】:

我搜索了在 AJV 架构中使用 if-then-else 的示例,但没有找到属性类型和所需列表根据另一个属性的值而更改的特定情况。

案例:

我需要升级userSchema,这样如果属性role = superuser,那么customer_id 既可以为空,也不需要。

const userSchema: Schema<UserItem> = {
  $schema: 'http://json-schema.org/draft-07/schema#',
  type: 'object',
  required: ['id', 'email', 'customer_id'],
  additionalProperties: false,
  properties: {
    id: {
      type: 'string',
      format: 'uuid'
    },
    email: {
      type: 'string',
      format: 'email'
    },
    customer_id: {
      type: 'string',
      format: 'uuid'
    },
    role: {
      anyOf: [
        { type: 'null' },
        { enum: Object.values(UserRole) }
      ]
    }
  }
}

我试过了……

const userSchemaNullableCustomerId: Schema<UserItem> = {
  ...userSchema,
  if: {
    properties: {
      role: { const: UserRole.Superuser }
    }
  },
  then: {
    properties: {
      customer_id: {
        anyOf: [
          { type: 'null' },
          { type: 'string', format: 'uuid' }
        ]
      }
    },
    not: {
      required: ['customer_id']
    }
  }
}

但它仍然抱怨data.customer_id should be string。怎么解决?

以下应该是正确的:

// Valid
{
    "id": "id",
    "email": "foo@bar.com",
    "role": "superuser",
    "customer_id": null
},
{
    "id": "id",
    "email": "foo@bar.com",
    "role": "superuser"
},
{
    "id": "id",
    "email": "foo@bar.com",
    "role": "null",
    "customer_id": 'some-uuid...'
},
{
    "id": "id",
    "email": "foo@bar.com",
    "role": "user",
    "customer_id": 'some-uuid...'
}

// Invalid
{
    "id": "id",
    "email": "foo@bar.com",
    "role": "user",
    "customer_id": null
},
{
    "id": "id",
    "email": "foo@bar.com",
    "role": "user"
},
{
    "id": "id",
    "email": "foo@bar.com",
    "role": "superuser",
    "customer_id": 'nonUuidString'
}

【问题讨论】:

    标签: javascript typescript ajv


    【解决方案1】:

    经过大量实验,我发现诀窍是必须将customer_id 属性初始化为空,而role 属性需要进行依赖性检查。

    ...
      properties: {
        id: {
          type: 'string',
          format: 'uuid'
        },
        email: {
          type: 'string',
          format: 'email'
        }
        customer_id: {},
        role: {
          anyOf: [
            { type: 'null' },
            { enum: Object.values(UserRole) }
          ]
        }
      },
      if: {
        dependencies: { role: ['role'] },
        properties: { role: { const: UserRole.Superuser } }
      },
      then: {
        properties: { customer_id: { anyOf: [{ type: 'null' }, { type: 'string', format: 'uuid' }] } }
      },
      else: {
        properties: { customer_id: { type: 'string', format: 'uuid' } }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      相关资源
      最近更新 更多