【问题标题】:Swagger: Representing enum property in hash errorSwagger:在哈希错误中表示枚举属性
【发布时间】:2020-03-24 19:13:53
【问题描述】:

我目前正在为 Ruby on Rails API 编写 Swagger 文档。 API 有很多枚举器(枚举),它们包含在各种模型中。枚举在 app/models/concerns 目录中存储为 hashes 而不是 arrays,以便以后可以修改它们而不会出现问题。

状态枚举 (state.rb)

module State
  extend ActiveSupport::Concern
  included do
    enum state: { state1: 'State 1',
                  state2: 'State 2',
                  state3: 'State 3',
                  state4: 'State 4',
                  state5: 'State 5' }
  end
end

但是,当我尝试在 Swagger 中的组件架构中表示这一点时:

components:
  schemas:
    State:
      type: object
      properties:
        enum: { state1: 'State 1',
                state2: 'State 2',
                state3: 'State 3',
                state4: 'State 4',
                state5: 'State 5' }

我收到一个错误:

不应该有额外的属性

state1: '状态 1'

state2: '状态 2'

state3: '状态 3'

state4: '状态 4'

state5: '状态 5'

我想在 hashes 中而不是在 arrays 中表示枚举。有什么解决方法可以让我完成这项工作吗?谢谢。

【问题讨论】:

  • 在阅读了通过您的链接提供的文档后,我尝试了这个:enum: - state1: 'State 1', - state2: 'State 2',但我得到了错误应该是对象。
  • 我对 swagger 不熟悉,但它似乎是一个 api 文档,因此 swagger 枚举中的值是您希望通过客户端传递给您的 api 的值,然后如果您想将其映射到其他值(即,“将 state1 作为参数传递以将值设置为 'State 1')您会使用描述功能将其作为文本说出来?就像我在某餐厅,我告诉他们我想要一杯大杯,他们知道这意味着 16 盎司,如果我想知道,我可以问他们那是多少;但我只需要知道我需要告诉他们“大”
  • 哈希值对枚举很有帮助,这样你就有了key:value 对,因为它反映在数据库中,不像把它放在描述中。
  • @SimpleLime 是正确的,因为 OpenAPI 枚举应该只定义操作期望/API 使用者将发送的实际值。消费者应该将"State 1""state1"{"state1": "State 1"} 作为对象或其他东西发送吗?请记住,OpenAPI 定义的是 API 契约,而不是数据库结构。

标签: ruby-on-rails ruby enums swagger openapi


【解决方案1】:

我终于找到了完成它的方法。 此解决方案适用于 OpenAPI 3 – 最新版本的 OpenAPI 规范作为回答此问题的重点。

我是这样做的

解决方案 1

components:
  schemas:
    State:
      type: object
      additionalProperties:
        type: string
      example:
        state1: State 1
        state2: State 2
        state3: State 3
        state4: State 4
        state5: State 5

这是将整个哈希传递到请求的响应正文中,因此会引发错误

解决方案 2:

另一种方法是将它们表示为数组,这不是我理想的解决方案,但它允许 Swagger 从数组中仅选择一项以传递到请求的响应正文中。但是,我会注意枚举是散列,我必须为客户端上的枚举执行 collection_selecthashes

components:
  schemas:
    State:
      type: string
      description: List of States
      enum:
        - State 1
        - State 2
        - State 3
        - State 4
        - State 5

最后,无论您选择哪种解决方案,您都可以在其他模型中引用它们,如下所示:

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          format: int64
        first_name:
          type: string
        last_name:
          type: string
        password:
          type: string
          format: password
        state:
          $ref: '#/components/schemas/State'

这里是 Swagger 文档的链接:Dictionaries, HashMaps and Associative Arrays

就是这样。

我希望这会有所帮助

【讨论】:

    猜你喜欢
    • 2013-04-10
    • 2011-05-02
    • 2012-02-16
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    相关资源
    最近更新 更多