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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48693335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:51:55  来源:igfitidea点击:

How to generate basic TypeScript interfaces from Swagger schema?

typescriptswaggercode-generation

提问by Ivan Koshelev

I'm looking for a way to generate simplistic TypeScript interfaces from a Swagger schema. Most solutions I find are needlessly complicated.

我正在寻找一种从 Swagger 模式生成简单的 TypeScript 接口的方法。我发现的大多数解决方案都是不必要的复杂。

I would like to generate interfaces like this:

我想生成这样的接口:

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,
}

From a schema like this:

从这样的模式:

    {
  "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": {}
}

回答by Amir Eldor

Not sure if that's a sane way to do this, it's the first time I'm playing around with Swagger.

不确定这是否是一种理智的方法,这是我第一次与 Swagger 一起玩。

I bumped into the following link and pasted the schema from the project I integrate with. From the top 'Generate Client' menu I chose one of the TypeScript presets and it generated a minimal project where I could extract the bits I needed, interface and classes, etc.

我碰到了以下链接并粘贴了我集成的项目中的架构。从顶部的“生成客户端”菜单中,我选择了一个 TypeScript 预设,它生成了一个最小的项目,我可以在其中提取我需要的位、界面和类等。

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

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

I tried running your schema. Here's a small excerpt of the generated code:

我尝试运行您的架构。这是生成的代码的一小段摘录:

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

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

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

Maybe with a bit more tweaking it can make exactly what you're looking for.

也许通过更多的调整,它可以完全满足您的需求。

Further reading may be about tools like https://github.com/swagger-api/swagger-codegenbut the online web editor is a quick and dirty way to do this.

进一步阅读可能是关于https://github.com/swagger-api/swagger-codegen之类的工具,但在线网络编辑器是一种快速而肮脏的方法。

回答by Amar Zavery - MSFT

You can also take a look at autorest.typescriptclient code generator. It provides good interfaces for all the model definitions, accurately defines readonly properties and enums. It supports a bunch of custom extensionsthat can be useful to improve the user experience of the generated client. You can take a look at some generated sample clients.

您还可以查看autorest.typescript客户端代码生成器。它为所有模型定义提供了良好的接口,准确定义了只读属性和枚举。它支持一系列自定义扩展,可用于改善生成的客户端的用户体验。您可以查看一些生成的示例客户端

Bonus: The generated typescript client works in node.js and also in the browser with the help of webpack.

奖励:生成的打字稿客户端可以在 node.js 中运行,也可以在 webpack 的帮助下在浏览器中运行。

回答by Alex Kon

You can try this tool sw2dts, which generated code like below:

你可以试试这个工具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;

The Color enum seems to need a little tweak, that should contain the names of properties to iterate over, instead of the real number.

Color 枚举似乎需要一些调整,它应该包含要迭代的属性名称,而不是实数。

回答by EnixCoda

I use dtsgenand it works well in my case.

我使用dtsgen,它在我的情况下运行良好。

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

回答by Clemens

Inspired by https://stackoverflow.com/a/43513850/4948492:

灵感来自https://stackoverflow.com/a/43513850/4948492

Swagger Codegengenerates server stubs and client SDKs for a variety of languages and frameworks, including Node.js.

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

To generate a Node.js server stub, run codegen with the -l nodejs-serverargument.

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

example (Mac):

示例(Mac):

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

回答by Sergey Volkov

I'm use swagger-typescript-apito generate interfaces from swagger schema

我使用swagger-typescript-api从 swagger 模式生成接口

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

回答by francoiscabrol

You can also just generate each interface from each schema with a simple json to typescript converter http://json2ts.com/. It's not fully automated but better than nothing... and simple.

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