首页 文章

昂首阔步的构成/继承

提问于
浏览
2

我正在尝试使用Swagger记录REST API . 我们API的简化JSON响应如下:

{ 
    "data": {
        "type": "person"
        "id": "1"
        "attributes": {
          "name": "Joe"
          "age": 32
          ...
        }
        "links": {
            ...
        }
    }
}

要么

{ 
    "data": {
        "type": "job"
        "id": "22"
        "attributes": {
          "name": "Manager"
          "location": "Somewhere"
          ...
        }
        "links": {
            ...
        }
    }
}

他们对成功GET的Swagger定义可能如下所示:

'200':
      description: OK.
      schema:
        type: object
        properties:
          data:
            type: object
            properties:
              id:
                type: string
              type:
                type: string
              attributes:
                $ref: '#/definitions/person'

要么

'200':
      description: OK.
      schema:
        type: object
        properties:
          data:
            type: object
            properties:
              id:
                type: string
              type:
                type: string
              attributes:
                $ref: '#/definitions/job'

在我们的Swagger文件中可能有很多重复 . 是否可以定义这些响应来共享公共部分?即我不想输入或复制/粘贴此部分数次:

'200':
      description: OK.
      schema:
        type: object
        properties:
          data:
            type: object
            properties:
              id:
                type: string
              type:
                type: string

我无法看到这如何使用鉴别器字段或使用$ ref .

1 回答

  • 2

    您可以使用 allOf 进行合成(与 discriminator 一起可以进行继承,但它不是真正的函数)

    allOf 与模式或引用数组一起使用,它将创建一个包含数组中所有定义的所有属性的新定义 .

    鉴于您希望某些定义共享 idtype 属性,它就是这样完成的:

    swagger: '2.0'
    info:
      version: 1.0.0
      title: API
    
    paths: {}
    
    definitions:
      SharedDefinition:
        properties:
          id:
            type: string
          type:
            type: string
    
      Person:
        allOf:
          - $ref: '#/definitions/SharedDefinition'
          - properties:
              firstname:
                type: string
              lastname:
                type: string
    
      JobSubDefinition:
        properties:
          name:
            type: string
    
      Job:
        allOf:
          - $ref: '#/definitions/SharedDefinition'
          - $ref: '#/definitions/JobSubDefinition'
    

    在这个例子中:

    • Person = SharedDefinition内联定义

    • Job = SharedDefinition JobSubDefinition

    更多关于这一点

相关问题