是否可以 "注入 "一个JSON Schema的引用?

问题描述 投票:1回答:1

考虑到我需要引用一个格式如下的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 以上,而不需要创建新的模式(所以这就像注入了 #components/schemas/ObjectA#components/schemas/ObjectB 成数据,只要需要)?)

我曾考虑使用 oneOf 但它不适合,因为只有特定的对象对特定的API端点有效(即使所有的对象都在数据属性下),而不是任何一个可用的对象。

json jsonschema openapi
1个回答
1
投票

在你的简单例子中,似乎没有必要重复使用简单的 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

根据实际的复杂程度,如果将共享部分简单复制,那么模式可能更容易阅读维护。

© www.soinside.com 2019 - 2024. All rights reserved.