@fxri/swagger2api 1.1.0 → 1.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -17
- package/dist/bin/index.cjs +1 -1
- package/dist/bin/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/package.json +8 -4
- package/.swaggerrc +0 -5
package/README.md
CHANGED
|
@@ -4,11 +4,31 @@
|
|
|
4
4
|
|
|
5
5
|
## ✨ 特性
|
|
6
6
|
|
|
7
|
-
- 🚀 **快速生成** - 从 Swagger JSON 快速生成 TS/JS
|
|
8
|
-
- 📁 **特性区别** - 利用现有参数拼接了新的 operationId 字段,避免了重名接口会出现【_n
|
|
9
|
-
- 📝 **拼接规则** - 将接口地址与请求方法拼接作为唯一ID,通过可选参数,将不带【{.+}】参数的【get】改为【query】作区分,然后移除【{.+}
|
|
10
|
-
- ⚙️ **环境依赖** - 工具需要在 node@20
|
|
11
|
-
- 🔧 **CLI 工具** - 更多参数可查看 swagger-typescript-api
|
|
7
|
+
- 🚀 **快速生成** - 从 Swagger JSON 快速生成 TS/JS 接口代码。
|
|
8
|
+
- 📁 **特性区别** - 利用现有参数拼接了新的 operationId 字段,避免了重名接口会出现【_n】后缀的情况。
|
|
9
|
+
- 📝 **拼接规则** - 将接口地址与请求方法拼接作为唯一ID,通过可选参数,将不带【{.+}】参数的【get】改为【query】作区分,然后移除【{.+}】参数,并移除地址的第一个参数。
|
|
10
|
+
- ⚙️ **环境依赖** - 工具需要在 node@20 及以上运行时环境下使用。
|
|
11
|
+
- 🔧 **CLI 工具** - 更多参数可查看 swagger-typescript-api 官方文档。
|
|
12
|
+
|
|
13
|
+
## 💡 功能简介
|
|
14
|
+
|
|
15
|
+
### 快速模式
|
|
16
|
+
|
|
17
|
+
1.直接使用配置文件参数,若配置文件不存在或者参数不全(如第一次运行该工具),则不会进入该模式。
|
|
18
|
+
|
|
19
|
+
### 指定配置
|
|
20
|
+
|
|
21
|
+
1.指定配置文件路径,支持多选,用【,】分隔。
|
|
22
|
+
|
|
23
|
+
2.使用该参数则不会触发扫描全部配置文件功能。
|
|
24
|
+
|
|
25
|
+
### 多文档配置
|
|
26
|
+
|
|
27
|
+
1.默认配置文档为saconfig.json,项目启动后会扫描当前项目下的所有符合【./**/saconfig*.json】规则的文件(如【saconfig.json】【saconfig.admin.json】【config/saconfig.json】等),并在扫描到多个文件是提供选择列表,如只有一个文件,则直接进入下一步,该功能可在配置项中关闭。
|
|
28
|
+
|
|
29
|
+
2.此功能扩展使用的话,可以作为一个独立工具使用,同时管理多个项目的接口配置。
|
|
30
|
+
|
|
31
|
+
3.搭配上快速模式和加载全部配置文件参数,可以实现一行命令更新所有项目的接口配置。
|
|
12
32
|
|
|
13
33
|
## 📦 安装
|
|
14
34
|
|
|
@@ -40,7 +60,7 @@ yarn add @fxri/swagger2api
|
|
|
40
60
|
|
|
41
61
|
在 `package.json` 中添加:
|
|
42
62
|
|
|
43
|
-
生成 axios http
|
|
63
|
+
生成 axios http 客户端,生成有关请求响应的附加信息,移除第一个前缀索引,使用快速模式。
|
|
44
64
|
|
|
45
65
|
```json
|
|
46
66
|
{
|
|
@@ -60,7 +80,7 @@ yarn add @fxri/swagger2api
|
|
|
60
80
|
|
|
61
81
|
### 1. 生成接口代码
|
|
62
82
|
|
|
63
|
-
如果没装过其他名字叫 swagger2api 的工具,那么在 shell 中直接使用就行,如果装过同名工具,则需要带上 @fxri
|
|
83
|
+
如果没装过其他名字叫 swagger2api 的工具,那么在 shell 中直接使用就行,如果装过同名工具,则需要带上 @fxri 作用域。
|
|
64
84
|
|
|
65
85
|
```bash
|
|
66
86
|
npx swagger2api
|
|
@@ -93,7 +113,7 @@ const api = new Api()
|
|
|
93
113
|
api.getUsers().then((res) => console.log(res))
|
|
94
114
|
```
|
|
95
115
|
|
|
96
|
-
每个方法会返回 Promise,可通过 async/await 或 .then()
|
|
116
|
+
每个方法会返回 Promise,可通过 async/await 或 .then() 处理响应。
|
|
97
117
|
|
|
98
118
|
## ⚙️ 配置选项
|
|
99
119
|
|
|
@@ -102,19 +122,29 @@ api.getUsers().then((res) => console.log(res))
|
|
|
102
122
|
| `url` | string | - | Swagger JSON 文件路径或 URL |
|
|
103
123
|
| `output` | string | `'./src/api'` | 生成代码的输出目录 |
|
|
104
124
|
| `name` | string | `'index'` | 接口文件名称,默认后缀为ts |
|
|
105
|
-
| `--
|
|
106
|
-
| `--
|
|
125
|
+
| `--quick,-q` | boolean | `false` | 快速模式,直接使用配置文件参数,不再二次确认参数 |
|
|
126
|
+
| `--config,-c` | string | `'saconfig.json'` | 填写配置文件路径,支持多选,用【,】分隔 |
|
|
127
|
+
| `--config-all,-ca` | boolean | `false` | 加载全部配置文件,不进行选择 |
|
|
128
|
+
| `--config-scan,-cs` | boolean | `true` | 扫描全部配置文件,并提供选择列表 |
|
|
107
129
|
| `--convert-get,-cg` | boolean | `false` | 转换无{.+}get为query |
|
|
108
130
|
| `--remove-param,-rp` | boolean | `false` | 移除{.+}参数 |
|
|
109
131
|
| `--remove-prefix-index,-rpi` | number | `-1` | 移除前缀索引 |
|
|
110
|
-
| `--remove-
|
|
132
|
+
| `--remove-dts,-rd` | boolean | `false` | 移除使用--js参数时生成的d.ts文件 |
|
|
111
133
|
|
|
112
134
|
扩展:[更多 swagger-typescript-api 配置选项](https://fig.io/manual/swagger-typescript-api)
|
|
113
135
|
|
|
114
136
|
## 🔧 CLI 命令
|
|
115
137
|
|
|
116
138
|
```bash
|
|
117
|
-
#
|
|
139
|
+
# 快速模式,直接使用配置文件参数,不再二次确认参数
|
|
140
|
+
|
|
141
|
+
npx swagger2api [--quick,-q] [--quick,-q <boolean>]
|
|
142
|
+
|
|
143
|
+
npx @fxri/swagger2api [--quick,-q] [--quick,-q <boolean>]
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
# 填写配置文件路径,支持多选,用【,】分隔,使用该配置后则不会触发配置扫描功能
|
|
118
148
|
|
|
119
149
|
npx swagger2api [--config,-c <path>]
|
|
120
150
|
|
|
@@ -122,11 +152,19 @@ npx @fxri/swagger2api [--config,-c <path>]
|
|
|
122
152
|
```
|
|
123
153
|
|
|
124
154
|
```bash
|
|
125
|
-
#
|
|
155
|
+
# 加载全部配置文件,不进行选择
|
|
126
156
|
|
|
127
|
-
npx swagger2api [--
|
|
157
|
+
npx swagger2api [--config-all,-ca] [--config-all,-ca <boolean>]
|
|
128
158
|
|
|
129
|
-
npx @fxri/swagger2api [--
|
|
159
|
+
npx @fxri/swagger2api [--config-all,-ca] [--config-all,-ca <boolean>]
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
# 扫描全部配置文件,并提供选择列表,该参数默认为true
|
|
164
|
+
|
|
165
|
+
npx swagger2api [--config-scan,-cs] [--config-scan,-cs <boolean>]
|
|
166
|
+
|
|
167
|
+
npx @fxri/swagger2api [--config-scan,-cs] [--config-scan,-cs <boolean>]
|
|
130
168
|
```
|
|
131
169
|
|
|
132
170
|
```bash
|
|
@@ -156,9 +194,9 @@ npx @fxri/swagger2api [--remove-prefix-index,-rpi <number>]
|
|
|
156
194
|
```bash
|
|
157
195
|
# 移除使用--js参数时生成的d.ts文件
|
|
158
196
|
|
|
159
|
-
npx swagger2api [--remove-
|
|
197
|
+
npx swagger2api [--remove-dts,-rd] [--remove-dts,-rd <boolean>]
|
|
160
198
|
|
|
161
|
-
npx @fxri/swagger2api [--remove-
|
|
199
|
+
npx @fxri/swagger2api [--remove-dts,-rd] [--remove-dts,-rd <boolean>]
|
|
162
200
|
```
|
|
163
201
|
|
|
164
202
|
## 🤝 贡献
|
package/dist/bin/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var A=Object.create;var x=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var D=(e,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of E(r))!q.call(e,i)&&i!==n&&x(e,i,{get:()=>r[i],enumerable:!(s=P(r,i))||s.enumerable});return e};var m=(e,r,n)=>(n=e!=null?A(T(e)):{},D(r||!e||!e.__esModule?x(n,"default",{value:e,enumerable:!0}):n,e));var j=m(require("axios"),1),O=require("child_process"),F=m(require("os"),1),g=m(require("fs"),1),c=m(require("path"),1),h=m(require("prompts"),1),N=require("swagger-typescript-api");var b=e=>/^(https?:\/\/|:?\/\/)/.test(e);var f=m(require("fs"),1),v=m(require("path"),1),u={param:process.argv.filter((e,r)=>r>1),used:{}};function w(e,r=!0,n=!0){Array.isArray(e)||(e=[e]);let s;return u.param.forEach((i,p)=>{if(e.includes(i))r?(s=u.param[p+1],n&&Object.assign(u.used,{[p+1]:!0})):["true","false"].includes(u.param[p+1])?(s=u.param[p+1].toLowerCase()=="true",n&&Object.assign(u.used,{[p+1]:!0})):s=!0;else return;n&&Object.assign(u.used,{[p]:!0})}),s}function a(e,r=!0){return w(e,!1,r)}function o(e,r=!0){return w(e,!0,r)}function d(e,r){let n=v.default.dirname(e);f.default.existsSync(n)||f.default.mkdirSync(n,{recursive:!0}),f.default.writeFileSync(e,r)}var $=require("glob"),t={files:[],param:{}},l={home:F.default.homedir(),enum:{}};function y(e){e&&console.log(e),process.exit()}async function C(){o(["--config","-c"])?t.files=o(["--config","-c"]).split(","):a(["--config-scan","-cs"])&&(t.files=$.glob.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),t.files.length==0&&(t.files=["saconfig.json"]),!a(["--config-all","-ca"])&&t.files.length>1&&(t.files=(await(0,h.default)({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:t.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:y("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),t.files?.length>0||y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function J(){try{t.param=JSON.parse(g.default.readFileSync(t.file,"utf-8"))}catch{}(!a(["--quick","-q"])||[t.param.url,t.param.output,t.param.name].includes(void 0))&&(t.param=await(0,h.default)([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:t.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:t.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:t.param.name??"index"}])),[t.param.url,t.param.output,t.param.name].includes(void 0)&&y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),l.docFile=c.default.resolve(`${t.param.output}/${t.param.name}-${new Date().getTime()}.json`)}async function k(e=0){if(t.file=t.files[e],await J(),b(t.param.url))await j.default.get(t.param.url).then(r=>S(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await S(JSON.parse(g.default.readFileSync(c.default.resolve(t.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}t.files[e+1]&&k(e+1)}async function S(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(r=>{Object.keys(r[1]).forEach(n=>{let s=`${r[0]}/${n}`;if(a(["--convert-get","-cg"])&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),a(["--remove-param","-rp"])&&(s=s.replace(/\/\{.+?\}/g,"")),o(["--remove-prefix-index","-rpi"])){let p=s.split("/");p=p.slice(0,1).concat(p.slice(Number(o(["--remove-prefix-index","-rpi"]))+2)),s=p.join("/")}e.paths[r[0]][n].operationId=s;let i=s.split("/").slice(-1)[0];typeof l.enum[i]=="number"?l.enum[i]++:l.enum[i]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(l.enum).map(r=>r.join("-"))),d(l.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",t.file),await(0,N.generateApi)({fileName:`${t.param.name}.ts`,output:c.default.resolve(t.param.output),input:l.docFile,templates:o(["--templates","-t"]),defaultResponseAsSuccess:a(["--default-as-success","-d"]),generateResponses:a(["--responses","-r"]),generateUnionEnums:a("--union-enums"),addReadonly:a("--add-readonly"),generateRouteTypes:a("--route-types"),generateClient:!a("--no-client"),enumNamesAsValues:a("--enum-names-as-values"),extractRequestParams:a("--extract-request-params"),extractRequestBody:a("--extract-request-body"),extractResponseBody:a("--extract-response-body"),extractResponseError:a("--extract-response-error"),modular:a("--modular"),toJS:a("--js"),moduleNameIndex:Number(o("--module-name-index")??0),moduleNameFirstTag:a("--module-name-first-tag"),httpClientType:a("--axios")?"axios":"fetch",unwrapResponseData:a("--unwrap-response-data"),disableThrowOnError:a("--disable-throw-on-error"),singleHttpClient:a("--single-http-client"),silent:a("--silent"),defaultResponseType:o("--default-response")??"void",typePrefix:o("--type-prefix")??"",typeSuffix:o("--type-suffix")??"",cleanOutput:a("--clean-output"),...o("--api-class-name")?{apiClassName:o("--api-class-name")}:{},patch:a("--patch"),debug:a("--debug"),anotherArrayType:a("--another-array-type"),sortTypes:a("--sort-types"),extractEnums:a("--extract-enums")}),g.default.unlinkSync(l.docFile),a(["--remove-dts","-rd"])&&(console.log("\u6E05\u7406\uFF1A",c.default.resolve(t.param.output,`${t.param.name}.d.ts`)),(0,O.execSync)(`npx rimraf ${c.default.resolve(t.param.output,`${t.param.name}.d.ts`)}`,{cwd:l.home}).toString()),d(t.file,JSON.stringify(t.param,null,2))}async function R(){await C(),k()}R();
|
package/dist/bin/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import j from"axios";import{execSync as O}from"child_process";import F from"os";import d from"fs";import u from"path";import b from"prompts";import{generateApi as N}from"swagger-typescript-api";var y=t=>/^(https?:\/\/|:?\/\/)/.test(t);import c from"fs";import S from"path";var l={param:process.argv.filter((t,r)=>r>1),used:{}};function h(t,r=!0,i=!0){Array.isArray(t)||(t=[t]);let s;return l.param.forEach((m,o)=>{if(t.includes(m))r?(s=l.param[o+1],i&&Object.assign(l.used,{[o+1]:!0})):["true","false"].includes(l.param[o+1])?(s=l.param[o+1].toLowerCase()=="true",i&&Object.assign(l.used,{[o+1]:!0})):s=!0;else return;i&&Object.assign(l.used,{[o]:!0})}),s}function a(t,r=!0){return h(t,!1,r)}function n(t,r=!0){return h(t,!0,r)}function f(t,r){let i=S.dirname(t);c.existsSync(i)||c.mkdirSync(i,{recursive:!0}),c.writeFileSync(t,r)}import{glob as $}from"glob";var e={files:[],param:{}},p={home:F.homedir(),enum:{}};function g(t){t&&console.log(t),process.exit()}async function k(){n(["--config","-c"])?e.files=n(["--config","-c"]).split(","):a(["--config-scan","-cs"])&&(e.files=$.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),e.files.length==0&&(e.files=["saconfig.json"]),!a(["--config-all","-ca"])&&e.files.length>1&&(e.files=(await b({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:e.files.map(t=>({title:t.replace(/\\/g,"/"),value:t}))}).then(t=>t.files?.length!=0?t:g("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),e.files?.length>0||g("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function R(){try{e.param=JSON.parse(d.readFileSync(e.file,"utf-8"))}catch{}(!a(["--quick","-q"])||[e.param.url,e.param.output,e.param.name].includes(void 0))&&(e.param=await b([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:e.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:e.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:e.param.name??"index"}])),[e.param.url,e.param.output,e.param.name].includes(void 0)&&g("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),p.docFile=u.resolve(`${e.param.output}/${e.param.name}-${new Date().getTime()}.json`)}async function v(t=0){if(e.file=e.files[t],await R(),y(e.param.url))await j.get(e.param.url).then(r=>x(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await x(JSON.parse(d.readFileSync(u.resolve(e.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}e.files[t+1]&&v(t+1)}async function x(t){if(typeof t?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(t.paths).forEach(r=>{Object.keys(r[1]).forEach(i=>{let s=`${r[0]}/${i}`;if(a(["--convert-get","-cg"])&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),a(["--remove-param","-rp"])&&(s=s.replace(/\/\{.+?\}/g,"")),n(["--remove-prefix-index","-rpi"])){let o=s.split("/");o=o.slice(0,1).concat(o.slice(Number(n(["--remove-prefix-index","-rpi"]))+2)),s=o.join("/")}t.paths[r[0]][i].operationId=s;let m=s.split("/").slice(-1)[0];typeof p.enum[m]=="number"?p.enum[m]++:p.enum[m]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(p.enum).map(r=>r.join("-"))),f(p.docFile,JSON.stringify(t)),console.log("\u6267\u884C\uFF1A",e.file),await N({fileName:`${e.param.name}.ts`,output:u.resolve(e.param.output),input:p.docFile,templates:n(["--templates","-t"]),defaultResponseAsSuccess:a(["--default-as-success","-d"]),generateResponses:a(["--responses","-r"]),generateUnionEnums:a("--union-enums"),addReadonly:a("--add-readonly"),generateRouteTypes:a("--route-types"),generateClient:!a("--no-client"),enumNamesAsValues:a("--enum-names-as-values"),extractRequestParams:a("--extract-request-params"),extractRequestBody:a("--extract-request-body"),extractResponseBody:a("--extract-response-body"),extractResponseError:a("--extract-response-error"),modular:a("--modular"),toJS:a("--js"),moduleNameIndex:Number(n("--module-name-index")??0),moduleNameFirstTag:a("--module-name-first-tag"),httpClientType:a("--axios")?"axios":"fetch",unwrapResponseData:a("--unwrap-response-data"),disableThrowOnError:a("--disable-throw-on-error"),singleHttpClient:a("--single-http-client"),silent:a("--silent"),defaultResponseType:n("--default-response")??"void",typePrefix:n("--type-prefix")??"",typeSuffix:n("--type-suffix")??"",cleanOutput:a("--clean-output"),...n("--api-class-name")?{apiClassName:n("--api-class-name")}:{},patch:a("--patch"),debug:a("--debug"),anotherArrayType:a("--another-array-type"),sortTypes:a("--sort-types"),extractEnums:a("--extract-enums")}),d.unlinkSync(p.docFile),a(["--remove-dts","-rd"])&&(console.log("\u6E05\u7406\uFF1A",u.resolve(e.param.output,`${e.param.name}.d.ts`)),O(`npx rimraf ${u.resolve(e.param.output,`${e.param.name}.d.ts`)}`,{cwd:p.home}).toString()),f(e.file,JSON.stringify(e.param,null,2))}async function w(){await k(),v()}w();
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var P=Object.create;var f=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var T=Object.getPrototypeOf,q=Object.prototype.hasOwnProperty;var D=(e,a)=>{for(var s in a)f(e,s,{get:a[s],enumerable:!0})},b=(e,a,s,n)=>{if(a&&typeof a=="object"||typeof a=="function")for(let i of E(a))!q.call(e,i)&&i!==s&&f(e,i,{get:()=>a[i],enumerable:!(n=A(a,i))||n.enumerable});return e};var m=(e,a,s)=>(s=e!=null?P(T(e)):{},b(a||!e||!e.__esModule?f(s,"default",{value:e,enumerable:!0}):s,e)),C=e=>b(f({},"__esModule",{value:!0}),e);var U={};D(U,{generateApi:()=>I});module.exports=C(U);var O=m(require("axios"),1),F=require("child_process"),N=m(require("os"),1),d=m(require("fs"),1),c=m(require("path"),1),x=m(require("prompts"),1),$=require("swagger-typescript-api");var v=e=>/^(https?:\/\/|:?\/\/)/.test(e);var g=m(require("fs"),1),w=m(require("path"),1),u={param:process.argv.filter((e,a)=>a>1),used:{}};function S(e,a=!0,s=!0){Array.isArray(e)||(e=[e]);let n;return u.param.forEach((i,p)=>{if(e.includes(i))a?(n=u.param[p+1],s&&Object.assign(u.used,{[p+1]:!0})):["true","false"].includes(u.param[p+1])?(n=u.param[p+1].toLowerCase()=="true",s&&Object.assign(u.used,{[p+1]:!0})):n=!0;else return;s&&Object.assign(u.used,{[p]:!0})}),n}function r(e,a=!0){return S(e,!1,a)}function o(e,a=!0){return S(e,!0,a)}function y(e,a){let s=w.default.dirname(e);g.default.existsSync(s)||g.default.mkdirSync(s,{recursive:!0}),g.default.writeFileSync(e,a)}var k=require("glob"),t={files:[],param:{}},l={home:N.default.homedir(),enum:{}};function h(e){e&&console.log(e),process.exit()}async function J(){o(["--config","-c"])?t.files=o(["--config","-c"]).split(","):r(["--config-scan","-cs"])&&(t.files=k.glob.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),t.files.length==0&&(t.files=["saconfig.json"]),!r(["--config-all","-ca"])&&t.files.length>1&&(t.files=(await(0,x.default)({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:t.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:h("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),t.files?.length>0||h("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function L(){try{t.param=JSON.parse(d.default.readFileSync(t.file,"utf-8"))}catch{}(!r(["--quick","-q"])||[t.param.url,t.param.output,t.param.name].includes(void 0))&&(t.param=await(0,x.default)([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:t.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:t.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:t.param.name??"index"}])),[t.param.url,t.param.output,t.param.name].includes(void 0)&&h("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),l.docFile=c.default.resolve(`${t.param.output}/${t.param.name}-${new Date().getTime()}.json`)}async function R(e=0){if(t.file=t.files[e],await L(),v(t.param.url))await O.default.get(t.param.url).then(a=>j(a.data)).catch(a=>console.log("\u5931\u8D25\uFF1A",a));else try{await j(JSON.parse(d.default.readFileSync(c.default.resolve(t.param.url),"utf8")))}catch(a){console.log("\u5931\u8D25\uFF1A",a)}t.files[e+1]&&R(e+1)}async function j(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(a=>{Object.keys(a[1]).forEach(s=>{let n=`${a[0]}/${s}`;if(r(["--convert-get","-cg"])&&(n=n.replace(/([^\}]\/)get$/g,"$1query")),r(["--remove-param","-rp"])&&(n=n.replace(/\/\{.+?\}/g,"")),o(["--remove-prefix-index","-rpi"])){let p=n.split("/");p=p.slice(0,1).concat(p.slice(Number(o(["--remove-prefix-index","-rpi"]))+2)),n=p.join("/")}e.paths[a[0]][s].operationId=n;let i=n.split("/").slice(-1)[0];typeof l.enum[i]=="number"?l.enum[i]++:l.enum[i]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(l.enum).map(a=>a.join("-"))),y(l.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",t.file),await(0,$.generateApi)({fileName:`${t.param.name}.ts`,output:c.default.resolve(t.param.output),input:l.docFile,templates:o(["--templates","-t"]),defaultResponseAsSuccess:r(["--default-as-success","-d"]),generateResponses:r(["--responses","-r"]),generateUnionEnums:r("--union-enums"),addReadonly:r("--add-readonly"),generateRouteTypes:r("--route-types"),generateClient:!r("--no-client"),enumNamesAsValues:r("--enum-names-as-values"),extractRequestParams:r("--extract-request-params"),extractRequestBody:r("--extract-request-body"),extractResponseBody:r("--extract-response-body"),extractResponseError:r("--extract-response-error"),modular:r("--modular"),toJS:r("--js"),moduleNameIndex:Number(o("--module-name-index")??0),moduleNameFirstTag:r("--module-name-first-tag"),httpClientType:r("--axios")?"axios":"fetch",unwrapResponseData:r("--unwrap-response-data"),disableThrowOnError:r("--disable-throw-on-error"),singleHttpClient:r("--single-http-client"),silent:r("--silent"),defaultResponseType:o("--default-response")??"void",typePrefix:o("--type-prefix")??"",typeSuffix:o("--type-suffix")??"",cleanOutput:r("--clean-output"),...o("--api-class-name")?{apiClassName:o("--api-class-name")}:{},patch:r("--patch"),debug:r("--debug"),anotherArrayType:r("--another-array-type"),sortTypes:r("--sort-types"),extractEnums:r("--extract-enums")}),d.default.unlinkSync(l.docFile),r(["--remove-dts","-rd"])&&(console.log("\u6E05\u7406\uFF1A",c.default.resolve(t.param.output,`${t.param.name}.d.ts`)),(0,F.execSync)(`npx rimraf ${c.default.resolve(t.param.output,`${t.param.name}.d.ts`)}`,{cwd:l.home}).toString()),y(t.file,JSON.stringify(t.param,null,2))}async function I(){await J(),R()}0&&(module.exports={generateApi});
|
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/**
|
|
2
|
-
declare function
|
|
1
|
+
/** 主线 */
|
|
2
|
+
declare function onMain(): Promise<void>;
|
|
3
3
|
|
|
4
|
-
export {
|
|
4
|
+
export { onMain as generateApi };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/**
|
|
2
|
-
declare function
|
|
1
|
+
/** 主线 */
|
|
2
|
+
declare function onMain(): Promise<void>;
|
|
3
3
|
|
|
4
|
-
export {
|
|
4
|
+
export { onMain as generateApi };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import S from"axios";import{execSync as j}from"child_process";import O from"os";import d from"fs";import u from"path";import b from"prompts";import{generateApi as F}from"swagger-typescript-api";var y=t=>/^(https?:\/\/|:?\/\/)/.test(t);import c from"fs";import w from"path";var l={param:process.argv.filter((t,r)=>r>1),used:{}};function h(t,r=!0,i=!0){Array.isArray(t)||(t=[t]);let s;return l.param.forEach((m,o)=>{if(t.includes(m))r?(s=l.param[o+1],i&&Object.assign(l.used,{[o+1]:!0})):["true","false"].includes(l.param[o+1])?(s=l.param[o+1].toLowerCase()=="true",i&&Object.assign(l.used,{[o+1]:!0})):s=!0;else return;i&&Object.assign(l.used,{[o]:!0})}),s}function a(t,r=!0){return h(t,!1,r)}function n(t,r=!0){return h(t,!0,r)}function f(t,r){let i=w.dirname(t);c.existsSync(i)||c.mkdirSync(i,{recursive:!0}),c.writeFileSync(t,r)}import{glob as N}from"glob";var e={files:[],param:{}},p={home:O.homedir(),enum:{}};function g(t){t&&console.log(t),process.exit()}async function $(){n(["--config","-c"])?e.files=n(["--config","-c"]).split(","):a(["--config-scan","-cs"])&&(e.files=N.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),e.files.length==0&&(e.files=["saconfig.json"]),!a(["--config-all","-ca"])&&e.files.length>1&&(e.files=(await b({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:e.files.map(t=>({title:t.replace(/\\/g,"/"),value:t}))}).then(t=>t.files?.length!=0?t:g("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),e.files?.length>0||g("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function k(){try{e.param=JSON.parse(d.readFileSync(e.file,"utf-8"))}catch{}(!a(["--quick","-q"])||[e.param.url,e.param.output,e.param.name].includes(void 0))&&(e.param=await b([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:e.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:e.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:e.param.name??"index"}])),[e.param.url,e.param.output,e.param.name].includes(void 0)&&g("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),p.docFile=u.resolve(`${e.param.output}/${e.param.name}-${new Date().getTime()}.json`)}async function v(t=0){if(e.file=e.files[t],await k(),y(e.param.url))await S.get(e.param.url).then(r=>x(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await x(JSON.parse(d.readFileSync(u.resolve(e.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}e.files[t+1]&&v(t+1)}async function x(t){if(typeof t?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(t.paths).forEach(r=>{Object.keys(r[1]).forEach(i=>{let s=`${r[0]}/${i}`;if(a(["--convert-get","-cg"])&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),a(["--remove-param","-rp"])&&(s=s.replace(/\/\{.+?\}/g,"")),n(["--remove-prefix-index","-rpi"])){let o=s.split("/");o=o.slice(0,1).concat(o.slice(Number(n(["--remove-prefix-index","-rpi"]))+2)),s=o.join("/")}t.paths[r[0]][i].operationId=s;let m=s.split("/").slice(-1)[0];typeof p.enum[m]=="number"?p.enum[m]++:p.enum[m]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(p.enum).map(r=>r.join("-"))),f(p.docFile,JSON.stringify(t)),console.log("\u6267\u884C\uFF1A",e.file),await F({fileName:`${e.param.name}.ts`,output:u.resolve(e.param.output),input:p.docFile,templates:n(["--templates","-t"]),defaultResponseAsSuccess:a(["--default-as-success","-d"]),generateResponses:a(["--responses","-r"]),generateUnionEnums:a("--union-enums"),addReadonly:a("--add-readonly"),generateRouteTypes:a("--route-types"),generateClient:!a("--no-client"),enumNamesAsValues:a("--enum-names-as-values"),extractRequestParams:a("--extract-request-params"),extractRequestBody:a("--extract-request-body"),extractResponseBody:a("--extract-response-body"),extractResponseError:a("--extract-response-error"),modular:a("--modular"),toJS:a("--js"),moduleNameIndex:Number(n("--module-name-index")??0),moduleNameFirstTag:a("--module-name-first-tag"),httpClientType:a("--axios")?"axios":"fetch",unwrapResponseData:a("--unwrap-response-data"),disableThrowOnError:a("--disable-throw-on-error"),singleHttpClient:a("--single-http-client"),silent:a("--silent"),defaultResponseType:n("--default-response")??"void",typePrefix:n("--type-prefix")??"",typeSuffix:n("--type-suffix")??"",cleanOutput:a("--clean-output"),...n("--api-class-name")?{apiClassName:n("--api-class-name")}:{},patch:a("--patch"),debug:a("--debug"),anotherArrayType:a("--another-array-type"),sortTypes:a("--sort-types"),extractEnums:a("--extract-enums")}),d.unlinkSync(p.docFile),a(["--remove-dts","-rd"])&&(console.log("\u6E05\u7406\uFF1A",u.resolve(e.param.output,`${e.param.name}.d.ts`)),j(`npx rimraf ${u.resolve(e.param.output,`${e.param.name}.d.ts`)}`,{cwd:p.home}).toString()),f(e.file,JSON.stringify(e.param,null,2))}async function G(){await $(),v()}export{G as generateApi};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fxri/swagger2api",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.2",
|
|
4
4
|
"description": "基于 swagger-typescript-api,将 Swagger 文档自动转为 TypeScript 格式的 API 文件。",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
@@ -14,17 +14,21 @@
|
|
|
14
14
|
"files": [
|
|
15
15
|
"dist",
|
|
16
16
|
"README.md",
|
|
17
|
-
".swaggerrc",
|
|
18
17
|
"package.json"
|
|
19
18
|
],
|
|
20
|
-
"keywords": [
|
|
19
|
+
"keywords": [
|
|
20
|
+
"swagger",
|
|
21
|
+
"typescript",
|
|
22
|
+
"api"
|
|
23
|
+
],
|
|
21
24
|
"dependencies": {
|
|
22
25
|
"axios": "^1.12.2",
|
|
26
|
+
"glob": "^11.0.3",
|
|
23
27
|
"prompts": "^2.4.2",
|
|
24
28
|
"swagger-typescript-api": "^13.2.15"
|
|
25
29
|
},
|
|
26
30
|
"devDependencies": {
|
|
27
|
-
"@types/node": "^
|
|
31
|
+
"@types/node": "^20.19.21",
|
|
28
32
|
"@types/prompts": "^2.4.9",
|
|
29
33
|
"@typescript-eslint/eslint-plugin": "^6.21.0",
|
|
30
34
|
"@typescript-eslint/parser": "^6.21.0",
|