【问题标题】:Does OpenAPI (Swagger) spec support generic objects for schema?OpenAPI (Swagger) 规范是否支持架构的通用对象?
【发布时间】:2020-06-13 23:09:39
【问题描述】:

我正在研究要在 C# 项目中使用的 OpenAPI 规范。我的 API 使用泛型类型,例如

    class Message<T>
    {
        public string Id { get; set; }
        public T Payload { get; set; }
    }

    class BasicClientState
    {
        public int Count { get; set; }
        public double FaultPercentage { get; set; }
    }

喜欢这个

    class SomeApiController
    {
        public Message<DateTime> GetLatestRebootMessage() 
        {
            throw new NotImplementedException();
        }
        public Message<BasicClientState> GetLatestBasicClientStateMessage()
        {
            throw new NotImplementedException();
        }
    }

这样的泛型能否在 OpenAPI 模式中表示,以便为具有泛型支持的语言(即 Java、TypeScript)生成的 DTO 也具有泛型类型?

【问题讨论】:

    标签: generics swagger openapi


    【解决方案1】:

    是的,但是您将丢失有关这些类的通用来源的信息。

    使用 swashbuckle 这是从生成的 swagger.json 中摘录的:

     "DateTimeMessage": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "nullable": true
          },
          "payload": {
            "type": "string",
            "format": "date-time"
          }
        },
        "additionalProperties": false
      },
      "BasicClientState": {
        "type": "object",
        "properties": {
          "count": {
            "type": "integer",
            "format": "int32"
          },
          "faultPercentage": {
            "type": "number",
            "format": "double"
          }
        },
        "additionalProperties": false
      },
      "BasicClientStateMessage": {
        "type": "object",
        "properties": {
          "id": {
            "type": "string",
            "nullable": true
          },
          "payload": {
            "$ref": "#/components/schemas/BasicClientState"
          }
        },
        "additionalProperties": false
      }
    

    【讨论】:

    • “是的,但是您将丢失有关这些类的通用来源的信息。” - 所以不行”。我的问题的关键部分 - “以便为具有泛型支持的语言(即 Java、TypeScript)生成的 DTO 也将具有泛型类型?”
    猜你喜欢
    • 1970-01-01
    • 2022-06-03
    • 2020-03-23
    • 1970-01-01
    • 2019-10-28
    • 2020-09-09
    • 2023-03-03
    • 1970-01-01
    • 2019-02-24
    相关资源
    最近更新 更多