0.0.4 • Published 1 year ago

swagger-to-ts-mods v0.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

欢迎使用 swagger-to-ts-mods 👋

Version Documentation License: MIT

中文文档 | English

swagger-to-ts-mods 根据 swagger文档生成typescript类型声明及api调用函数

安装

# 使用 npm
npm install swagger-to-ts-mods

# 使用 yarn
yarn add swagger-to-ts-mods

使用

# 生成配置文件
$ s2t setup

# 生成类型声明及api函数
$ s2t generate

# 查看说明
$ s2t [command] -h

生成示例

API.d.ts

declare namespace API {
  namespace User {
    interface Exception {
      cause?: Throwable;
      localizedMessage?: string;
      message?: string;
      stackTrace?: StackTraceElement[];
      suppressed?: Throwable[];
    }
    interface RestVo {
      code?: number;
      data?: { ... };
      exception?: Exception;
      message?: string;
    }
    /** login */
    namespace postAuthsLogin {
      type Query = {
        /** checkcode */
        code?: string;
        /** phone */
        mobile?: string;
        /** password */
        password?: string;
        /** account */
        username?: string;
      };

      type Response = RestVo;
    }
  }
  
  namespace File { ... }
  ...
}

some-operation.ts

e.g. postAuthsLogin.ts

import uRequest from "@/services";

import Inter = API.User.postAuthsLogin;

/** login */
export function postAuthsLogin(query: Inter.Query): Promise<Inter.Response> {
  return uRequest<Inter.Response>("/api/v1/auths/login", {
    method: "post",
    params: query,
  });
}

命令

$ s2t setup [outputPath]

生成配置文件

参数默认值是否必填说明
outputPath"./s2t.config.json"指定配置文件输出地址

$ s2t generate [configPath]

根据配置文件生成目标文件

参数默认值是否必填说明
configPath"./s2t.config.json"用于指定配置文件地址

配置文件

s2t.config.json

key类型默认值是否必填说明
requestRequestConfigRequestConfig通用api请求设置
handleUnknownTypeunknown | generic | anyunknown如何处理未知类型 (暂未实现)
outputDirPath"./services"生成文件的目录
templateDirPath内置生成类型声明及api函数时的模板文件目录
originsOriginConfig[]指定swagger文档地址来源

OriginConfig

key类型默认值是否必填说明
originstringswagger文档地址
originNamestring指定该文档名称
requestRequestConfigRequestConfig为该文档指定特殊请求设置

RequestConfig

生成api函数时指定基类函数的引入方式

如: import ${methodName} from "${filePath}"

key类型默认值是否必填说明
filePathPath"@/request"指定本地接口调用函数
methodNamestringrequest指定导出的函数名
defaultbooleantrue方法是否为默认导出

模板文件

使用mustache作为渲染引擎

模板内容说明
API.d.mustache内置声明文件模板
operation.mustache内置api模板

TODOS:

  • 支持$ref中远程文档的解析
  • 处理未知类型时,支持泛型