Javascript 基于枚举的AJV if-then-else条件类型
我搜索了在AJV模式中使用Javascript 基于枚举的AJV if-then-else条件类型,javascript,typescript,ajv,Javascript,Typescript,Ajv,我搜索了在AJV模式中使用if-then-else的示例,但没有找到属性类型和所需列表根据另一个属性的值更改的特定情况 案例: 我需要升级userSchema,这样如果属性role=superuser,那么customer\u id既可以为空,也不需要 const userSchema: Schema<UserItem> = { $schema: 'http://json-schema.org/draft-07/schema#', type: 'object', requ
if-then-else
的示例,但没有找到属性类型和所需列表根据另一个属性的值更改的特定情况
案例:
我需要升级userSchema
,这样如果属性role
=superuser
,那么customer\u 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) }
]
}
}
}
经过多次实验,我发现诀窍在于
customer\u 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' } }
}
// 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'
}
...
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' } }
}