使用额外的必填字段扩展 $ref
Extending $ref with additional required fields
给定一个名为 location
的模式的一部分,如下所示:
{
type: 'object',
required: [ 'country' ],
additionalProperties: false,
properties: {
country: {
enum: [ 'DE', 'CH', 'AT' ],
},
postalCode: { type: 'string' },
},
};
在我们的大多数用例中,仅给定国家/地区代码的位置是有效的。但是,在某些情况下,我们也必须要求提供邮政编码。
例如,在我们的例子中,一家公司总是需要邮政编码。当然,我们之前的 location
架构不强制执行此操作。其他模式需要不强制存在邮政编码的位置对象。这是我们公司的架构:
{
type: 'object',
required: [ 'name', 'location' ],
additionalProperties: false,
properties: {
location: { $ref: 'location' },
name: { type: 'string' },
website: { type: 'string' },
},
};
在 JSON 模式中有没有一种方法可以使用 $ref 并扩展它,以便 company
模式中的 location
属性 将自动需要一个postalCode
?我们目前的解决方案是基于 location
创建第二个模式,我们只是更改了 required
属性,但我希望有更好的方法。
谢谢。
你可以
{
type: 'object',
required: [ 'name', 'location' ],
additionalProperties: false,
properties: {
location: {
allOf: [
{ $ref: 'location' },
{ required: [ 'postalCode' ] }
]
},
name: { type: 'string' },
website: { type: 'string' }
}
}
给定一个名为 location
的模式的一部分,如下所示:
{
type: 'object',
required: [ 'country' ],
additionalProperties: false,
properties: {
country: {
enum: [ 'DE', 'CH', 'AT' ],
},
postalCode: { type: 'string' },
},
};
在我们的大多数用例中,仅给定国家/地区代码的位置是有效的。但是,在某些情况下,我们也必须要求提供邮政编码。
例如,在我们的例子中,一家公司总是需要邮政编码。当然,我们之前的 location
架构不强制执行此操作。其他模式需要不强制存在邮政编码的位置对象。这是我们公司的架构:
{
type: 'object',
required: [ 'name', 'location' ],
additionalProperties: false,
properties: {
location: { $ref: 'location' },
name: { type: 'string' },
website: { type: 'string' },
},
};
在 JSON 模式中有没有一种方法可以使用 $ref 并扩展它,以便 company
模式中的 location
属性 将自动需要一个postalCode
?我们目前的解决方案是基于 location
创建第二个模式,我们只是更改了 required
属性,但我希望有更好的方法。
谢谢。
你可以
{
type: 'object',
required: [ 'name', 'location' ],
additionalProperties: false,
properties: {
location: {
allOf: [
{ $ref: 'location' },
{ required: [ 'postalCode' ] }
]
},
name: { type: 'string' },
website: { type: 'string' }
}
}