【发布时间】: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