考虑到我需要引用以下格式的 json:
{
"data": {
"type": "ObjectA"
}
}
当我为此 json 请求编写 JSON 架构(或更具体地说,OpenAPI 规范 v3.0.3 的架构对象)时,我会编写
components:
schemas:
Data:
type: object
required:
- data
properties:
data:
$ref: '#components/schemas/ObjectA'
ObjectA:
type: object
properties:
type:
type: string
ObjectB:
type: object
properties:
type:
type: string
some_properties:
type: string
...我使用 $ref: '#components/schemas/Data'
引用它。
但是现在还有另一个 json 需要处理,它与上面的非常相似,只是 data
属性中的对象不是 ObjectA
类型,它是 ObjectB
。
{
"data": {
"type": "ObjectB",
"some_properties": "which is different from ObjectA"
}
}
有没有办法让我重用上面的 Data
架构而不创建新架构(所以这就像注入(inject) #components/schemas/ObjectA
或 #components/schemas/ObjectB
在需要时插入数据)?
我考虑过使用 oneOf
但它不适合,因为只有特定对象对特定 API 端点有效(即使所有对象都在 data 属性下),而不是任何一个可用对象.
最佳答案
在您的简单示例中,似乎没有必要重新使用简单的 Data
定义。但是,假设您的实际结构更复杂,您可以通过 allOf
将一般属性与特定属性组合起来,例如
components:
schemas:
BaseData:
type: object
required:
- data
properties:
data:
type: object
properties:
type:
type: string
required:
- type
DataA:
allOf:
- $ref: '#components/schemas/BaseData'
- type: object
properties:
data:
$ref: '#components/schemas/ObjectA'
DataB:
allOf:
- $ref: '#components/schemas/BaseData'
- type: object
properties:
data:
$ref: '#components/schemas/ObjectB'
ObjectA:
type: object
properties:
type:
const: ObjectA
ObjectB:
type: object
properties:
type:
const: ObjectB
some_properties:
type: string
required:
- some_properties
根据实际的复杂性,如果简单地复制共享部分,架构可能会更容易阅读/维护。
关于json - 是否可以 'inject' 引用 JSON 架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61975987/