Swagger(OpenAPI) 生成ts模板代码

203 阅读1分钟

1.使用Swagger生成ts代码,先看效果。

image.png image.png image.png

image.png

2.解决痛点

  • 在使用ts带来的便利的同时,又烦够了类型体操。每次后端的一点点接口的变动,不仅需要去修改业务逻辑,还需要去维护数据类型。
  • 同每次新项目启动,都需要去迁移一次axios模板代码。
  • 每次对接接口时都需要花费大量的时间去写请求接口。

孫悟空-西遊記.gif

3.废话不多说,开撸

a.安装 Install

$ npm install --save swagger-to-apis

or

$ yarn add swagger-to-apis

b.在根目录创建脚本文件

create your swagger-to-apis.ts file

import { swaggerToApis } from "swagger-to-apis";

// Currently supports v2 and v3.0
swaggerToApis({
  // TODO: 注意 这需要修改
  url: "https://petstore.swagger.io/v2/swagger.json", // 改成你项目的接口文档json文件地址
  output: "./src", // 输出地址
});

c.在package.json添加脚本命令

Add the script in your package.json file.

    "api": "npx tsx swagger-to-apis.ts",

d.运输脚本

Run the script
$ npm run api

你就可以看到生成了对应的文件结构

image.png

更改你的baseURL Change baseURL

View src/apis/http.ts, on the 11 line;

const baseURL = '/'; // change to your base url
更改服务端返回的结构体类型 Change Api.Response interface

View src/apis/api.d.ts, on the 11 line;


  // If your API does not have an outer wrapper
  type Response<T> = T;

  // Your API has an outer layer that can be customized to modify the current structure
  // interface Response<T> {
  //   code: number;
  //   msg: string;
  //   message: string;
  //   data: T;
  // }

使用 Use

import { Api } from 'src/apis';

let pet_info: Api.SwaggerV2.Pet;

const res = await Api.SwaggerV2Api.get_pet_petId(1);
if (Api.isSuccess(res)) {
  pet_info = res.data
}

Examples

GitHub

祝你:代码五分钟,摸鱼两小时!