基于枚举的AJV if-then-else条件类型

时间:2020-08-31 16:29:00

标签: javascript typescript ajv

我已经搜索了在AJV模式中使用<base target="_top"> </head> <body> <p>Hey <?= meta.name ?>!</p> <p>Congratulations! You made it! ? ? ? ? </p> 的示例,但是还没有发现特定类型的情况,即属性类型和所需列表根据另一个属性的值而改变。

案例:

我需要升级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

1 个答案:

答案 0 :(得分:0)

经过大量实验,我发现诀窍在于必须将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' } }
  }