如何从Swagger模式生成基本的TypeScript接口?

62

我正在寻找一种从Swagger模式生成简单TypeScript接口的方法。大多数我找到的解决方案都过于复杂。

我希望生成类似于以下这样的接口:

export interface IBar {
    a?: string;
    b: number;
    c: Date;
    baz?: IBaz;
}

export interface IBaz {
    d: number;
    color: Color;
}

export enum Color {
    RED = 0,
    GREEN = 1,
    BLUE = 2,
}

从这样的架构开始:

    {
  "x-generator": "NSwag v11.14.0.0 (NJsonSchema v9.10.24.0 (Newtonsoft.Json v9.0.0.0))",
  "swagger": "2.0",
  "info": {
    "title": "",
    "version": ""
  },
  "schemes": [],
  "consumes": [
    "application/json"
  ],
  "produces": [
    "application/json"
  ],
  "paths": {
    "/api/Foo/GetBarDescriptions": {
      "get": {
        "tags": [
          "Foo"
        ],
        "operationId": "Foo_GetBarDescriptions",
        "parameters": [],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "type": "array",
              "items": {
                "type": "string"
              }
            },
            "x-nullable": true
          }
        }
      }
    },
    "/api/Foo/GetBar": {
      "get": {
        "tags": [
          "Foo"
        ],
        "operationId": "Foo_GetBar",
        "parameters": [
          {
            "type": "integer",
            "name": "id",
            "in": "query",
            "required": true,
            "x-nullable": false,
            "format": "int32"
          }
        ],
        "responses": {
          "200": {
            "description": "",
            "schema": {
              "$ref": "#/definitions/Bar"
            },
            "x-nullable": true
          }
        }
      }
    },
    "/api/Foo/SetBar": {
      "post": {
        "tags": [
          "Foo"
        ],
        "operationId": "Foo_SetBar",
        "parameters": [
          {
            "name": "value",
            "in": "body",
            "required": true,
            "schema": {
              "$ref": "#/definitions/Bar"
            },
            "x-nullable": true
          }
        ],
        "responses": {
          "204": {
            "description": ""
          }
        }
      }
    }
  },
  "definitions": {
    "Bar": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "B",
        "C"
      ],
      "properties": {
        "A": {
          "type": "string"
        },
        "B": {
          "type": "integer",
          "format": "int32"
        },
        "C": {
          "type": "string",
          "format": "date-time"
        },
        "Baz": {
          "$ref": "#/definitions/Baz"
        }
      }
    },
    "Baz": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "D",
        "Color"
      ],
      "properties": {
        "D": {
          "type": "number",
          "format": "decimal"
        },
        "Color": {
          "$ref": "#/definitions/Color"
        }
      }
    },
    "Color": {
      "type": "integer",
      "description": "",
      "x-enumNames": [
        "RED",
        "GREEN",
        "BLUE"
      ],
      "enum": [
        0,
        1,
        2
      ]
    }
  },
  "parameters": {},
  "responses": {},
  "securityDefinitions": {}
}

1
我可能误解了你或这个链接,但是你上面生成的模式引用了NSwag。它的文档声称集成了AutoRest(在下面列出的解决方案之一)。也许这是新的,但它说“该项目将Swashbuckle(OpenAPI / Swagger生成)和AutoRest(客户端生成)的功能结合在一个工具链中。”来自:https://github.com/RicoSuter/NSwag。我正在调查这个问题,完成后会再次评论。 - shannon
1
是的,这很容易。更困难的部分是为模式生成设置项目,因为注释和其他因素必须符合Swagger / NSwag的期望。由于在上面的示例中已经完成了这一点,NSwagStudio只需单击即可生成TypeScript,并可以保存配置以供自动化工具链使用。我唯一的抱怨是提供的模板非常糟糕...超过90%的默认生成的代理/客户端代码包含应该是一次声明的分离关注点的重复内容,并且默认DTO模板包含我无法消除的意外类型联合。 - shannon
9个回答

25

我不确定这是否是一种明智的做法,这是我第一次尝试使用Swagger。

我发现了以下链接,并粘贴了与项目集成的模式。从顶部的“生成客户端”菜单中,我选择了其中一个TypeScript预设,并生成了一个最小的项目,我可以从中提取所需的位、接口和类等。

http://editor.swagger.io/#/

我尝试运行您的方案。下面是生成代码的一小部分:

export interface Bar {
    "a"?: string;
    "b": number;
    "c": Date;
    "baz"?: Baz;
}

export interface Baz {
    "d": number;
    "color": Color;
}

/**
 * 
 */
export type Color = "0" | "1" | "2";

也许稍微调整一下,它就能做出你想要的东西。

更多阅读可能涉及到像https://github.com/swagger-api/swagger-codegen这样的工具,但在线网页编辑器是一种快速而简便的方法。


对于当前情况,我决定选择 http://json-schema.org/ 而非 swagger,并使用 https://github.com/RSuter/NJsonSchema 进行生成。我仍在寻找未来案例的最佳代码生成器(当然是针对 NodeJS 的),最好是使用 JS 插值字符串而不是第三方模板引擎。 - Ivan Koshelev

22

我正在使用swagger-typescript-api从Swagger架构生成接口

npx swagger-typescript-api -p PATH_TO_YOUR_SCHEMA -o ./

-o ./ means output directory to be ./ and it is the default value, so it's not necessary to list it explicitly. In addition, maybe parameter -n could be mentioned, which means name of the generated file, by default this is Api.ts. I'm using -n apiObjects.ts - Frimlik
有没有可能将每个定义放入额外的文件中? - Frimlik
@Frimlik,您可以使用modular选项+ NodeJS API + single-http-client选项来生成额外的文件。 - Sergey Volkov
这个程序很容易运行,但生成的文件无法使用,因为它具有一个神秘的通用类型参数。 - Richard Barraclough
@SergeyVolkov,你有没有做这个的例子?我在我的data-contracts.ts中有所有相关的接口,但不幸的是,无论CLI选项如何,我都无法将它们提取到单独的文件中。我需要做什么才能完成这个任务? - Igor

12

我使用 dtsgenerator,在我的情况下它运作良好。

yarn dtsgen --out ./path/to/generated-types.d.ts ./path/to/input/swagger.json.or.yml

6
您还可以查看autorest.typescript客户端代码生成器。它为所有模型定义提供良好的接口,准确定义只读属性和枚举。它支持一些自定义扩展,可以有助于改善所生成的客户端的用户体验。您可以查看一些生成的示例客户端
附赠:生成的TypeScript客户端可以在node.js中运行,并且借助webpack也可以在浏览器中运行。

6
你可以尝试使用这个工具 sw2dts,它可以生成以下代码:
export interface Bar {
    A?: string;
    B: number; // int32
    C: string; // date-time
    Baz?: Baz;
}
export interface Baz {
    D: number; // decimal
    Color: Color;
}
/**
 * 
 */
export type Color = 0 | 1 | 2;
枚举似乎需要进行一些微调,应该包含要迭代的属性名称而不是实际数字。

5

我正在寻找一个可以生成类型而不是可运行代码的软件包。我认为这与问题中的要求相同。目前我发现的最接近只生成类型的软件包是:

https://www.npmjs.com/package/@manifoldco/swagger-to-ts

使用 @manifoldco/swagger-to-ts 的 2.0.0 版本将会为问题中的模式生成如下内容:

/**
 * This file was auto-generated by swagger-to-ts.
 * Do not make direct changes to the file.
 */

export interface definitions {
  Bar: { A?: string; B: number; C: string; Baz?: definitions["Baz"] };
  Baz: { D: number; Color: definitions["Color"] };
  Color: "0" | "1" | "2";
}

注意:有一个同名的包没有任何组织前缀。请确保尝试带有@manifoldco前缀的那个包。一开始我错过了这个细节,非常困惑 :-)。


此软件包已被弃用。它已被以下替代品所取代:https://www.npmjs.com/package/openapi-typescript - vcarel

4
  1. 首先从Swagger下载schema.json文件
  2. 安装OpenAPI(它也适用于JavaScript和TypeScript)
  3. 运行
npx openapi-typescript https://example.com/swagger/v1/swagger.json --output generated-type.ts

现在你可以在项目文件夹中看到一个 .ts 文件被创建了。(如果使用的是 .js,请将 .ts 替换为 .js)


无法工作。抱怨无效的 JSON - 在其他生成器可以使用相同的文件中。 - Richard Barraclough

2

https://dev59.com/ZKHia4cB1Zd3GeqPNQw5#43513850启发:

Swagger Codegen可为多种语言和框架生成服务器存根和客户端SDK,包括Node.js。

要生成Node.js服务器存根,请使用-l nodejs-server参数运行代码生成器。

示例(Mac):

swagger-codegen generate -l typescript-angular -i swagger.yaml -o ~/Downloads/ts-test

1
你也可以使用简单的json到typescript转换器http://json2ts.com/从每个模式生成每个接口。 它并不是完全自动化的,但总比什么都没有要好......而且很简单。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接