@fxri/swagger2api 1.1.7 → 1.1.9
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 +43 -6
- package/dist/cli.cjs +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/templates/api.ejs +69 -69
- package/dist/templates/http-client.ejs +151 -155
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -65,13 +65,13 @@ yarn add @fxri/swagger2api
|
|
|
65
65
|
```json
|
|
66
66
|
{
|
|
67
67
|
"scripts": {
|
|
68
|
-
"api": "swagger2api --axios --responses
|
|
68
|
+
"api": "swagger2api --axios --responses -q -rpi 0 -err"
|
|
69
69
|
}
|
|
70
70
|
}
|
|
71
71
|
|
|
72
72
|
{
|
|
73
73
|
"scripts": {
|
|
74
|
-
"api": "npx @fxri/swagger2api --axios --responses
|
|
74
|
+
"api": "npx @fxri/swagger2api --axios --responses -q -rpi 0 -err"
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
77
|
```
|
|
@@ -107,10 +107,37 @@ npx @fxri/swagger2api
|
|
|
107
107
|
直接调用生成的API类方法:
|
|
108
108
|
|
|
109
109
|
```typescript
|
|
110
|
-
import { Api } from "./
|
|
110
|
+
import { Api } from "./api"
|
|
111
|
+
/** 请求器 */
|
|
112
|
+
export const request = new Api()
|
|
113
|
+
request.getUsers().then((res) => console.log(res))
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### 4. 提取响应(如没有使用提取响应参数,则忽略该项)
|
|
117
|
+
|
|
118
|
+
声明自定义的根部字段(以下字段为示例,请根据实际情况自行调整):
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
declare module "." {
|
|
122
|
+
interface AxiosResponseRaw<T = any> {
|
|
123
|
+
/** 状态代码 */
|
|
124
|
+
code: number
|
|
125
|
+
/** 提示信息 */
|
|
126
|
+
message: string
|
|
127
|
+
/** 响应数据 */
|
|
128
|
+
data: T["data"]
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
```
|
|
111
132
|
|
|
112
|
-
|
|
113
|
-
|
|
133
|
+
根据已声明字段,配置对应的返回值:
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
// 响应拦截
|
|
137
|
+
client.instance.interceptors.response.use(
|
|
138
|
+
(response) => ({ code: 0, data: null, message: "", raw: response }),
|
|
139
|
+
(error) => ({ code: -1, data: null, message: error.message, raw: error })
|
|
140
|
+
)
|
|
114
141
|
```
|
|
115
142
|
|
|
116
143
|
每个方法会返回 Promise,可通过 async/await 或 .then() 处理响应。
|
|
@@ -126,12 +153,13 @@ api.getUsers().then((res) => console.log(res))
|
|
|
126
153
|
| `--config,-c` | string | `'saconfig.json'` | 填写配置文件路径,支持多选,用【,】分隔 |
|
|
127
154
|
| `--config-all,-ca` | boolean | `false` | 加载全部配置文件,不进行选择 |
|
|
128
155
|
| `--config-scan,-cs` | boolean | `true` | 扫描全部配置文件,并提供选择列表 |
|
|
156
|
+
| `--replace-tags,-rt` | string[] | - | 替换标签,2个参数,第1个正则表达式(已包含^$头尾),第2个替换字符串 |
|
|
129
157
|
| `--convert-get,-cg` | boolean | `false` | 转换无{.+}get为query |
|
|
130
158
|
| `--remove-param,-rp` | boolean | `false` | 移除{.+}参数 |
|
|
131
159
|
| `--remove-prefix-index,-rpi` | number | `-1` | 移除前缀索引 |
|
|
132
160
|
| `--remove-dts,-rd` | boolean | `false` | 移除使用--js参数时生成的d.ts文件 |
|
|
133
161
|
| `--extract-request-query,-erq` | string | - | 提取参数,将query参数中的指定对象字段提取为根部字段,支持多选,用【,】分隔,每个接口只提取第一次命中的字段 |
|
|
134
|
-
| `--extract-response-raw,-err` | boolean | `false` | 提取响应,将AxiosResponse返回值转移到raw
|
|
162
|
+
| `--extract-response-raw,-err` | boolean | `false` | 提取响应,将AxiosResponse返回值转移到raw字段,根部字段自行定义,使用该参数需在响应拦截中重新设计实际的返回值 |
|
|
135
163
|
|
|
136
164
|
扩展:[更多 swagger-typescript-api 配置选项](https://fig.io/manual/swagger-typescript-api)
|
|
137
165
|
|
|
@@ -151,6 +179,7 @@ npx @fxri/swagger2api [--quick,-q] [--quick,-q <boolean>]
|
|
|
151
179
|
npx swagger2api [--config,-c <path>]
|
|
152
180
|
|
|
153
181
|
npx @fxri/swagger2api [--config,-c <path>]
|
|
182
|
+
```
|
|
154
183
|
|
|
155
184
|
```bash
|
|
156
185
|
# 移除前缀索引
|
|
@@ -160,6 +189,14 @@ npx swagger2api [--remove-prefix-index,-rpi <number>]
|
|
|
160
189
|
npx @fxri/swagger2api [--remove-prefix-index,-rpi <number>]
|
|
161
190
|
```
|
|
162
191
|
|
|
192
|
+
```bash
|
|
193
|
+
# 替换标签,2个参数,第1个正则表达式(已包含^$头尾),第2个替换字符串
|
|
194
|
+
|
|
195
|
+
npx swagger2api [--replace-tags,-rt <regexp> <substr>]
|
|
196
|
+
|
|
197
|
+
npx @fxri/swagger2api [--replace-tags,-rt <regexp> <substr>]
|
|
198
|
+
```
|
|
199
|
+
|
|
163
200
|
## 🤝 贡献
|
|
164
201
|
|
|
165
202
|
欢迎提交 Issue 和 Pull Request!
|
package/dist/cli.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var E=Object.create;var S=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var _=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty;var C=(e,t,s,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of J(t))!I.call(e,i)&&i!==s&&S(e,i,{get:()=>t[i],enumerable:!(o=O(t,i))||o.enumerable});return e};var c=(e,t,s)=>(s=e!=null?E(_(e)):{},C(t||!e||!e.__esModule?S(s,"default",{value:e,enumerable:!0}):s,e));var A=c(require("axios"),1),R=require("child_process"),T=c(require("os"),1),g=c(require("fs"),1),l=c(require("path"),1),v=c(require("prompts"),1),j=require("swagger-typescript-api");var w=e=>/^(https?:\/\/|:?\/\/)/.test(e);var f=c(require("fs"),1),P=c(require("url"),1),d=c(require("path"),1),U={},u={param:process.argv.filter((e,t)=>t>1)};function y(e,t="value",s={}){Array.isArray(e)||(e=[e]);let o;return u.param.forEach((i,m)=>{if(e.includes(i))["value"].includes(t)?o=u.param[m+1]:["array"].includes(t)?o=Array.from({length:s.length??1}).map((K,N)=>u.param[m+N+1]):o=!["false"].includes(u.param[m+1]);else return}),o}function r(e){return y(e,"key")}function p(e){return y(e,"value")}function b(e,t={}){return y(e,"array",t)??[]}function x(e,t){let s=d.default.dirname(e);f.default.existsSync(s)||f.default.mkdirSync(s,{recursive:!0}),f.default.writeFileSync(e,t)}function L(){return typeof require<"u"&&typeof module<"u"?__filename:P.default.fileURLToPath(U.url)}function $(){return typeof require<"u"&&typeof module<"u"?__dirname:d.default.dirname(L())}var k=require("glob"),a={files:[],param:{}},n={home:T.default.homedir(),enum:{}};function h(e){e&&console.log(e),process.exit()}async function G(){n.param={config:p(["--config","-c"]),configScan:r(["--config-scan","-cs"]),configAll:r(["--config-all","-ca"]),quick:r(["--quick","-q"]),replaceTags:b(["--replace-tags","-rt"],{length:2}),convertGet:r(["--convert-get","-cg"]),removeParam:r(["--remove-param","-rp"]),removePrefixIndex:p(["--remove-prefix-index","-rpi"]),removeDts:r(["--remove-dts","-rd"]),extractRequestQuery:p(["--extract-request-query","-erq"]),extractResponseRaw:r(["--extract-response-raw","-err"]),template:l.default.resolve($(),"./templates")},n.config={templates:p(["--templates","-t"])??n.param.template,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(p("--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")??!0,defaultResponseType:p("--default-response")??"void",typePrefix:p("--type-prefix")??"",typeSuffix:p("--type-suffix")??"",cleanOutput:r("--clean-output"),...p("--api-class-name")?{apiClassName:p("--api-class-name")}:{},patch:r("--patch"),debug:r("--debug"),anotherArrayType:r("--another-array-type"),sortTypes:r("--sort-types"),extractEnums:r("--extract-enums")}}async function V(){n.param.config?a.files=n.param.config.split(","):(n.param.configScan??!0)&&(a.files=k.glob.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!n.param.configAll&&a.files.length>1&&(a.files=(await(0,v.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:a.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),a.files?.length>0||h("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function B(){try{a.param={},a.param=JSON.parse(g.default.readFileSync(a.file,"utf-8"))}catch{}(!n.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await(0,v.default)([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&h("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),n.docFile=l.default.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function D(e=0){if(a.file=a.files[e],await B(),w(a.param.url))await A.default.get(a.param.url).then(t=>q(t.data)).catch(t=>console.log("\u5931\u8D25\uFF1A",t));else try{await q(JSON.parse(g.default.readFileSync(l.default.resolve(a.param.url),"utf8")))}catch(t){console.log("\u5931\u8D25\uFF1A",t)}a.files[e+1]&&D(e+1)}async function q(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(t=>{Object.keys(t[1]).forEach(s=>{n.param.replaceTags.length&&(e.paths[t[0]][s].tags=e.paths[t[0]][s].tags?.map(m=>m.replace(new RegExp(`^${n.param.replaceTags[0]}$`,"g"),n.param.replaceTags[1]??"")));let o=`${t[0]}/${s}`;if(n.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),n.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),n.param.removePrefixIndex){let m=o.split("/");m=m.slice(0,1).concat(m.slice(Number(n.param.removePrefixIndex)+2)),o=m.join("/")}e.paths[t[0]][s].operationId=o;let i=o.split("/").slice(-1)[0];typeof n.enum[i]=="number"?n.enum[i]++:n.enum[i]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(n.enum).map(t=>t.join("-"))),x(n.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await(0,j.generateApi)({fileName:`${a.param.name}.ts`,output:l.default.resolve(a.param.output),input:n.docFile,...n.config,param:n.param}),console.log("\u5B8C\u6210\uFF1A",l.default.resolve(a.param.output,`${a.param.name}${n.config.toJS?".js":".ts"}`)),n.config.toJS&&console.log("\u5B8C\u6210\uFF1A",l.default.resolve(a.param.output,`${a.param.name}.d.ts`)),g.default.unlinkSync(n.docFile),n.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",l.default.resolve(a.param.output,`${a.param.name}.d.ts`)),(0,R.execSync)(`npx rimraf ${l.default.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:n.home}).toString()),x(a.file,JSON.stringify(a.param,null,2))}async function F(){await G(),await V(),D()}F();
|
package/dist/cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var u=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,s)=>(typeof require<"u"?require:n)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import j from"axios";import{execSync as k}from"child_process";import D from"os";import x from"fs";import m from"path";import b from"prompts";import{generateApi as F}from"swagger-typescript-api";var h=e=>/^(https?:\/\/|:?\/\/)/.test(e);import f from"fs";import R from"url";import v from"path";var c={param:process.argv.filter((e,n)=>n>1)};function g(e,n="value",s={}){Array.isArray(e)||(e=[e]);let o;return c.param.forEach((l,p)=>{if(e.includes(l))["value"].includes(n)?o=c.param[p+1]:["array"].includes(n)?o=Array.from({length:s.length??1}).map((_,A)=>c.param[p+A+1]):o=!["false"].includes(c.param[p+1]);else return}),o}function r(e){return g(e,"key")}function i(e){return g(e,"value")}function S(e,n={}){return g(e,"array",n)??[]}function d(e,n){let s=v.dirname(e);f.existsSync(s)||f.mkdirSync(s,{recursive:!0}),f.writeFileSync(e,n)}function T(){return typeof u<"u"&&typeof module<"u"?__filename:R.fileURLToPath(import.meta.url)}function w(){return typeof u<"u"&&typeof module<"u"?__dirname:v.dirname(T())}import{glob as N}from"glob";var a={files:[],param:{}},t={home:D.homedir(),enum:{}};function y(e){e&&console.log(e),process.exit()}async function E(){t.param={config:i(["--config","-c"]),configScan:r(["--config-scan","-cs"]),configAll:r(["--config-all","-ca"]),quick:r(["--quick","-q"]),replaceTags:S(["--replace-tags","-rt"],{length:2}),convertGet:r(["--convert-get","-cg"]),removeParam:r(["--remove-param","-rp"]),removePrefixIndex:i(["--remove-prefix-index","-rpi"]),removeDts:r(["--remove-dts","-rd"]),extractRequestQuery:i(["--extract-request-query","-erq"]),extractResponseRaw:r(["--extract-response-raw","-err"]),template:m.resolve(w(),"./templates")},t.config={templates:i(["--templates","-t"])??t.param.template,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(i("--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")??!0,defaultResponseType:i("--default-response")??"void",typePrefix:i("--type-prefix")??"",typeSuffix:i("--type-suffix")??"",cleanOutput:r("--clean-output"),...i("--api-class-name")?{apiClassName:i("--api-class-name")}:{},patch:r("--patch"),debug:r("--debug"),anotherArrayType:r("--another-array-type"),sortTypes:r("--sort-types"),extractEnums:r("--extract-enums")}}async function O(){t.param.config?a.files=t.param.config.split(","):(t.param.configScan??!0)&&(a.files=N.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!t.param.configAll&&a.files.length>1&&(a.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:a.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),a.files?.length>0||y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function J(){try{a.param={},a.param=JSON.parse(x.readFileSync(a.file,"utf-8"))}catch{}(!t.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await b([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),t.docFile=m.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function $(e=0){if(a.file=a.files[e],await J(),h(a.param.url))await j.get(a.param.url).then(n=>P(n.data)).catch(n=>console.log("\u5931\u8D25\uFF1A",n));else try{await P(JSON.parse(x.readFileSync(m.resolve(a.param.url),"utf8")))}catch(n){console.log("\u5931\u8D25\uFF1A",n)}a.files[e+1]&&$(e+1)}async function P(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(n=>{Object.keys(n[1]).forEach(s=>{t.param.replaceTags.length&&(e.paths[n[0]][s].tags=e.paths[n[0]][s].tags?.map(p=>p.replace(new RegExp(`^${t.param.replaceTags[0]}$`,"g"),t.param.replaceTags[1]??"")));let o=`${n[0]}/${s}`;if(t.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),t.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),t.param.removePrefixIndex){let p=o.split("/");p=p.slice(0,1).concat(p.slice(Number(t.param.removePrefixIndex)+2)),o=p.join("/")}e.paths[n[0]][s].operationId=o;let l=o.split("/").slice(-1)[0];typeof t.enum[l]=="number"?t.enum[l]++:t.enum[l]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(t.enum).map(n=>n.join("-"))),d(t.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await F({fileName:`${a.param.name}.ts`,output:m.resolve(a.param.output),input:t.docFile,...t.config,param:t.param}),console.log("\u5B8C\u6210\uFF1A",m.resolve(a.param.output,`${a.param.name}${t.config.toJS?".js":".ts"}`)),t.config.toJS&&console.log("\u5B8C\u6210\uFF1A",m.resolve(a.param.output,`${a.param.name}.d.ts`)),x.unlinkSync(t.docFile),t.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",m.resolve(a.param.output,`${a.param.name}.d.ts`)),k(`npx rimraf ${m.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:t.home}).toString()),d(a.file,JSON.stringify(a.param,null,2))}async function q(){await E(),await O(),$()}q();
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var E=Object.create;var u=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var _=Object.getPrototypeOf,I=Object.prototype.hasOwnProperty;var C=(e,r)=>{for(var o in r)u(e,o,{get:r[o],enumerable:!0})},w=(e,r,o,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of J(r))!I.call(e,i)&&i!==o&&u(e,i,{get:()=>r[i],enumerable:!(s=O(r,i))||s.enumerable});return e};var c=(e,r,o)=>(o=e!=null?E(_(e)):{},w(r||!e||!e.__esModule?u(o,"default",{value:e,enumerable:!0}):o,e)),L=e=>w(u({},"__esModule",{value:!0}),e);var M={};C(M,{generateApi:()=>H});module.exports=L(M);var A=c(require("axios"),1),T=require("child_process"),j=c(require("os"),1),d=c(require("fs"),1),m=c(require("path"),1),S=c(require("prompts"),1),k=require("swagger-typescript-api");var P=e=>/^(https?:\/\/|:?\/\/)/.test(e);var g=c(require("fs"),1),b=c(require("url"),1),y=c(require("path"),1),G={},f={param:process.argv.filter((e,r)=>r>1)};function x(e,r="value",o={}){Array.isArray(e)||(e=[e]);let s;return f.param.forEach((i,l)=>{if(e.includes(i))["value"].includes(r)?s=f.param[l+1]:["array"].includes(r)?s=Array.from({length:o.length??1}).map((Q,N)=>f.param[l+N+1]):s=!["false"].includes(f.param[l+1]);else return}),s}function t(e){return x(e,"key")}function p(e){return x(e,"value")}function $(e,r={}){return x(e,"array",r)??[]}function h(e,r){let o=y.default.dirname(e);g.default.existsSync(o)||g.default.mkdirSync(o,{recursive:!0}),g.default.writeFileSync(e,r)}function U(){return typeof require<"u"&&typeof module<"u"?__filename:b.default.fileURLToPath(G.url)}function q(){return typeof require<"u"&&typeof module<"u"?__dirname:y.default.dirname(U())}var D=require("glob"),a={files:[],param:{}},n={home:j.default.homedir(),enum:{}};function v(e){e&&console.log(e),process.exit()}async function V(){n.param={config:p(["--config","-c"]),configScan:t(["--config-scan","-cs"]),configAll:t(["--config-all","-ca"]),quick:t(["--quick","-q"]),replaceTags:$(["--replace-tags","-rt"],{length:2}),convertGet:t(["--convert-get","-cg"]),removeParam:t(["--remove-param","-rp"]),removePrefixIndex:p(["--remove-prefix-index","-rpi"]),removeDts:t(["--remove-dts","-rd"]),extractRequestQuery:p(["--extract-request-query","-erq"]),extractResponseRaw:t(["--extract-response-raw","-err"]),template:m.default.resolve(q(),"./templates")},n.config={templates:p(["--templates","-t"])??n.param.template,defaultResponseAsSuccess:t(["--default-as-success","-d"]),generateResponses:t(["--responses","-r"]),generateUnionEnums:t("--union-enums"),addReadonly:t("--add-readonly"),generateRouteTypes:t("--route-types"),generateClient:!t("--no-client"),enumNamesAsValues:t("--enum-names-as-values"),extractRequestParams:t("--extract-request-params"),extractRequestBody:t("--extract-request-body"),extractResponseBody:t("--extract-response-body"),extractResponseError:t("--extract-response-error"),modular:t("--modular"),toJS:t("--js"),moduleNameIndex:Number(p("--module-name-index")??0),moduleNameFirstTag:t("--module-name-first-tag"),httpClientType:t("--axios")?"axios":"fetch",unwrapResponseData:t("--unwrap-response-data"),disableThrowOnError:t("--disable-throw-on-error"),singleHttpClient:t("--single-http-client"),silent:t("--silent")??!0,defaultResponseType:p("--default-response")??"void",typePrefix:p("--type-prefix")??"",typeSuffix:p("--type-suffix")??"",cleanOutput:t("--clean-output"),...p("--api-class-name")?{apiClassName:p("--api-class-name")}:{},patch:t("--patch"),debug:t("--debug"),anotherArrayType:t("--another-array-type"),sortTypes:t("--sort-types"),extractEnums:t("--extract-enums")}}async function B(){n.param.config?a.files=n.param.config.split(","):(n.param.configScan??!0)&&(a.files=D.glob.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!n.param.configAll&&a.files.length>1&&(a.files=(await(0,S.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:a.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:v("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),a.files?.length>0||v("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function K(){try{a.param={},a.param=JSON.parse(d.default.readFileSync(a.file,"utf-8"))}catch{}(!n.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await(0,S.default)([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&v("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),n.docFile=m.default.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function F(e=0){if(a.file=a.files[e],await K(),P(a.param.url))await A.default.get(a.param.url).then(r=>R(r.data)).catch(r=>console.log("\u5931\u8D25\uFF1A",r));else try{await R(JSON.parse(d.default.readFileSync(m.default.resolve(a.param.url),"utf8")))}catch(r){console.log("\u5931\u8D25\uFF1A",r)}a.files[e+1]&&F(e+1)}async function R(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(o=>{n.param.replaceTags.length&&(e.paths[r[0]][o].tags=e.paths[r[0]][o].tags?.map(l=>l.replace(new RegExp(`^${n.param.replaceTags[0]}$`,"g"),n.param.replaceTags[1]??"")));let s=`${r[0]}/${o}`;if(n.param.convertGet&&(s=s.replace(/([^\}]\/)get$/g,"$1query")),n.param.removeParam&&(s=s.replace(/\/\{.+?\}/g,"")),n.param.removePrefixIndex){let l=s.split("/");l=l.slice(0,1).concat(l.slice(Number(n.param.removePrefixIndex)+2)),s=l.join("/")}e.paths[r[0]][o].operationId=s;let i=s.split("/").slice(-1)[0];typeof n.enum[i]=="number"?n.enum[i]++:n.enum[i]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(n.enum).map(r=>r.join("-"))),h(n.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await(0,k.generateApi)({fileName:`${a.param.name}.ts`,output:m.default.resolve(a.param.output),input:n.docFile,...n.config,param:n.param}),console.log("\u5B8C\u6210\uFF1A",m.default.resolve(a.param.output,`${a.param.name}${n.config.toJS?".js":".ts"}`)),n.config.toJS&&console.log("\u5B8C\u6210\uFF1A",m.default.resolve(a.param.output,`${a.param.name}.d.ts`)),d.default.unlinkSync(n.docFile),n.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",m.default.resolve(a.param.output,`${a.param.name}.d.ts`)),(0,T.execSync)(`npx rimraf ${m.default.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:n.home}).toString()),h(a.file,JSON.stringify(a.param,null,2))}async function H(){await V(),await B(),F()}0&&(module.exports={generateApi});
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var u=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,s)=>(typeof require<"u"?require:n)[s]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import T from"axios";import{execSync as j}from"child_process";import k from"os";import x from"fs";import l from"path";import b from"prompts";import{generateApi as D}from"swagger-typescript-api";var h=e=>/^(https?:\/\/|:?\/\/)/.test(e);import f from"fs";import R from"url";import v from"path";var c={param:process.argv.filter((e,n)=>n>1)};function g(e,n="value",s={}){Array.isArray(e)||(e=[e]);let o;return c.param.forEach((m,p)=>{if(e.includes(m))["value"].includes(n)?o=c.param[p+1]:["array"].includes(n)?o=Array.from({length:s.length??1}).map((J,q)=>c.param[p+q+1]):o=!["false"].includes(c.param[p+1]);else return}),o}function r(e){return g(e,"key")}function i(e){return g(e,"value")}function S(e,n={}){return g(e,"array",n)??[]}function d(e,n){let s=v.dirname(e);f.existsSync(s)||f.mkdirSync(s,{recursive:!0}),f.writeFileSync(e,n)}function A(){return typeof u<"u"&&typeof module<"u"?__filename:R.fileURLToPath(import.meta.url)}function w(){return typeof u<"u"&&typeof module<"u"?__dirname:v.dirname(A())}import{glob as F}from"glob";var a={files:[],param:{}},t={home:k.homedir(),enum:{}};function y(e){e&&console.log(e),process.exit()}async function N(){t.param={config:i(["--config","-c"]),configScan:r(["--config-scan","-cs"]),configAll:r(["--config-all","-ca"]),quick:r(["--quick","-q"]),replaceTags:S(["--replace-tags","-rt"],{length:2}),convertGet:r(["--convert-get","-cg"]),removeParam:r(["--remove-param","-rp"]),removePrefixIndex:i(["--remove-prefix-index","-rpi"]),removeDts:r(["--remove-dts","-rd"]),extractRequestQuery:i(["--extract-request-query","-erq"]),extractResponseRaw:r(["--extract-response-raw","-err"]),template:l.resolve(w(),"./templates")},t.config={templates:i(["--templates","-t"])??t.param.template,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(i("--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")??!0,defaultResponseType:i("--default-response")??"void",typePrefix:i("--type-prefix")??"",typeSuffix:i("--type-suffix")??"",cleanOutput:r("--clean-output"),...i("--api-class-name")?{apiClassName:i("--api-class-name")}:{},patch:r("--patch"),debug:r("--debug"),anotherArrayType:r("--another-array-type"),sortTypes:r("--sort-types"),extractEnums:r("--extract-enums")}}async function E(){t.param.config?a.files=t.param.config.split(","):(t.param.configScan??!0)&&(a.files=F.sync(["./**/saconfig*.json"],{ignore:"node_modules/**"})),a.files.length==0&&(a.files=["saconfig.json"]),!t.param.configAll&&a.files.length>1&&(a.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:a.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),a.files?.length>0||y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function O(){try{a.param={},a.param=JSON.parse(x.readFileSync(a.file,"utf-8"))}catch{}(!t.param.quick||[a.param.url,a.param.output,a.param.name].includes(void 0))&&(a.param=await b([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:a.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:a.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:a.param.name??"index"}])),[a.param.url,a.param.output,a.param.name].includes(void 0)&&y("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),t.docFile=l.resolve(`${a.param.output}/${a.param.name}-${new Date().getTime()}.json`)}async function $(e=0){if(a.file=a.files[e],await O(),h(a.param.url))await T.get(a.param.url).then(n=>P(n.data)).catch(n=>console.log("\u5931\u8D25\uFF1A",n));else try{await P(JSON.parse(x.readFileSync(l.resolve(a.param.url),"utf8")))}catch(n){console.log("\u5931\u8D25\uFF1A",n)}a.files[e+1]&&$(e+1)}async function P(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");Object.entries(e.paths).forEach(n=>{Object.keys(n[1]).forEach(s=>{t.param.replaceTags.length&&(e.paths[n[0]][s].tags=e.paths[n[0]][s].tags?.map(p=>p.replace(new RegExp(`^${t.param.replaceTags[0]}$`,"g"),t.param.replaceTags[1]??"")));let o=`${n[0]}/${s}`;if(t.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),t.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),t.param.removePrefixIndex){let p=o.split("/");p=p.slice(0,1).concat(p.slice(Number(t.param.removePrefixIndex)+2)),o=p.join("/")}e.paths[n[0]][s].operationId=o;let m=o.split("/").slice(-1)[0];typeof t.enum[m]=="number"?t.enum[m]++:t.enum[m]=1})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(t.enum).map(n=>n.join("-"))),d(t.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",a.file),await D({fileName:`${a.param.name}.ts`,output:l.resolve(a.param.output),input:t.docFile,...t.config,param:t.param}),console.log("\u5B8C\u6210\uFF1A",l.resolve(a.param.output,`${a.param.name}${t.config.toJS?".js":".ts"}`)),t.config.toJS&&console.log("\u5B8C\u6210\uFF1A",l.resolve(a.param.output,`${a.param.name}.d.ts`)),x.unlinkSync(t.docFile),t.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",l.resolve(a.param.output,`${a.param.name}.d.ts`)),j(`npx rimraf ${l.resolve(a.param.output,`${a.param.name}.d.ts`)}`,{cwd:t.home}).toString()),d(a.file,JSON.stringify(a.param,null,2))}async function ne(){await N(),await E(),$()}export{ne as generateApi};
|
package/dist/templates/api.ejs
CHANGED
|
@@ -1,69 +1,69 @@
|
|
|
1
|
-
<%
|
|
2
|
-
const { apiConfig, routes, utils, config } = it;
|
|
3
|
-
const { info, servers, externalDocs } = apiConfig;
|
|
4
|
-
const { _, require, formatDescription } = utils;
|
|
5
|
-
|
|
6
|
-
const server = (servers && servers[0]) || { url: "" };
|
|
7
|
-
|
|
8
|
-
const descriptionLines = _.compact([
|
|
9
|
-
`@title ${info.title || "No title"}`,
|
|
10
|
-
info.version && `@version ${info.version}`,
|
|
11
|
-
info.license && `@license ${_.compact([
|
|
12
|
-
info.license.name,
|
|
13
|
-
info.license.url && `(${info.license.url})`,
|
|
14
|
-
]).join(" ")}`,
|
|
15
|
-
info.termsOfService && `@termsOfService ${info.termsOfService}`,
|
|
16
|
-
server.url && `@baseUrl ${server.url}`,
|
|
17
|
-
externalDocs.url && `@externalDocs ${externalDocs.url}`,
|
|
18
|
-
info.contact && `@contact ${_.compact([
|
|
19
|
-
info.contact.name,
|
|
20
|
-
info.contact.email && `<${info.contact.email}>`,
|
|
21
|
-
info.contact.url && `(${info.contact.url})`,
|
|
22
|
-
]).join(" ")}`,
|
|
23
|
-
info.description && " ",
|
|
24
|
-
info.description && _.replace(formatDescription(info.description), /\n/g, "\n * "),
|
|
25
|
-
]);
|
|
26
|
-
|
|
27
|
-
%>
|
|
28
|
-
|
|
29
|
-
<% if (config.httpClientType === config.constants.HTTP_CLIENT.AXIOS) { %> import type { AxiosRequestConfig, AxiosResponse } from "axios"; <% } %>
|
|
30
|
-
|
|
31
|
-
<% if (descriptionLines.length) { %>
|
|
32
|
-
/**
|
|
33
|
-
<% descriptionLines.forEach((descriptionLine) => { %>
|
|
34
|
-
* <%~ descriptionLine %>
|
|
35
|
-
|
|
36
|
-
<% }) %>
|
|
37
|
-
*/
|
|
38
|
-
<% } %>
|
|
39
|
-
export class <%~ config.apiClassName %><SecurityDataType extends unknown><% if (!config.singleHttpClient) { %> extends HttpClient<SecurityDataType> <% } %> {
|
|
40
|
-
|
|
41
|
-
<% if(config.singleHttpClient) { %>
|
|
42
|
-
http: HttpClient<SecurityDataType>;
|
|
43
|
-
|
|
44
|
-
constructor (http: HttpClient<SecurityDataType>) {
|
|
45
|
-
this.http = http;
|
|
46
|
-
}
|
|
47
|
-
<% } %>
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
<% if (routes.outOfModule) { %>
|
|
51
|
-
<% for (const route of routes.outOfModule) { %>
|
|
52
|
-
|
|
53
|
-
<%~ includeFile('./procedure-call.ejs', { ...it, route }) %>
|
|
54
|
-
|
|
55
|
-
<% } %>
|
|
56
|
-
<% } %>
|
|
57
|
-
|
|
58
|
-
<% if (routes.combined) { %>
|
|
59
|
-
<% for (const { routes: combinedRoutes = [], moduleName } of routes.combined) { %>
|
|
60
|
-
<%~ moduleName %> = {
|
|
61
|
-
<% for (const route of combinedRoutes) { %>
|
|
62
|
-
|
|
63
|
-
<%~ includeFile('./procedure-call.ejs', { ...it, route }) %>
|
|
64
|
-
|
|
65
|
-
<% } %>
|
|
66
|
-
}
|
|
67
|
-
<% } %>
|
|
68
|
-
<% } %>
|
|
69
|
-
}
|
|
1
|
+
<%
|
|
2
|
+
const { apiConfig, routes, utils, config } = it;
|
|
3
|
+
const { info, servers, externalDocs } = apiConfig;
|
|
4
|
+
const { _, require, formatDescription } = utils;
|
|
5
|
+
|
|
6
|
+
const server = (servers && servers[0]) || { url: "" };
|
|
7
|
+
|
|
8
|
+
const descriptionLines = _.compact([
|
|
9
|
+
`@title ${info.title || "No title"}`,
|
|
10
|
+
info.version && `@version ${info.version}`,
|
|
11
|
+
info.license && `@license ${_.compact([
|
|
12
|
+
info.license.name,
|
|
13
|
+
info.license.url && `(${info.license.url})`,
|
|
14
|
+
]).join(" ")}`,
|
|
15
|
+
info.termsOfService && `@termsOfService ${info.termsOfService}`,
|
|
16
|
+
server.url && `@baseUrl ${server.url}`,
|
|
17
|
+
externalDocs.url && `@externalDocs ${externalDocs.url}`,
|
|
18
|
+
info.contact && `@contact ${_.compact([
|
|
19
|
+
info.contact.name,
|
|
20
|
+
info.contact.email && `<${info.contact.email}>`,
|
|
21
|
+
info.contact.url && `(${info.contact.url})`,
|
|
22
|
+
]).join(" ")}`,
|
|
23
|
+
info.description && " ",
|
|
24
|
+
info.description && _.replace(formatDescription(info.description), /\n/g, "\n * "),
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
%>
|
|
28
|
+
|
|
29
|
+
<% if (config.httpClientType === config.constants.HTTP_CLIENT.AXIOS && !config.param?.extractResponseRaw) { %> import type { AxiosRequestConfig, AxiosResponse } from "axios"; <% } %>
|
|
30
|
+
|
|
31
|
+
<% if (descriptionLines.length) { %>
|
|
32
|
+
/**
|
|
33
|
+
<% descriptionLines.forEach((descriptionLine) => { %>
|
|
34
|
+
* <%~ descriptionLine %>
|
|
35
|
+
|
|
36
|
+
<% }) %>
|
|
37
|
+
*/
|
|
38
|
+
<% } %>
|
|
39
|
+
export class <%~ config.apiClassName %><SecurityDataType extends unknown><% if (!config.singleHttpClient) { %> extends HttpClient<SecurityDataType> <% } %> {
|
|
40
|
+
|
|
41
|
+
<% if(config.singleHttpClient) { %>
|
|
42
|
+
http: HttpClient<SecurityDataType>;
|
|
43
|
+
|
|
44
|
+
constructor (http: HttpClient<SecurityDataType>) {
|
|
45
|
+
this.http = http;
|
|
46
|
+
}
|
|
47
|
+
<% } %>
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
<% if (routes.outOfModule) { %>
|
|
51
|
+
<% for (const route of routes.outOfModule) { %>
|
|
52
|
+
|
|
53
|
+
<%~ includeFile('./procedure-call.ejs', { ...it, route }) %>
|
|
54
|
+
|
|
55
|
+
<% } %>
|
|
56
|
+
<% } %>
|
|
57
|
+
|
|
58
|
+
<% if (routes.combined) { %>
|
|
59
|
+
<% for (const { routes: combinedRoutes = [], moduleName } of routes.combined) { %>
|
|
60
|
+
<%~ moduleName %> = {
|
|
61
|
+
<% for (const route of combinedRoutes) { %>
|
|
62
|
+
|
|
63
|
+
<%~ includeFile('./procedure-call.ejs', { ...it, route }) %>
|
|
64
|
+
|
|
65
|
+
<% } %>
|
|
66
|
+
}
|
|
67
|
+
<% } %>
|
|
68
|
+
<% } %>
|
|
69
|
+
}
|
|
@@ -1,155 +1,151 @@
|
|
|
1
|
-
<%
|
|
2
|
-
const { apiConfig, generateResponses, config } = it;
|
|
3
|
-
%>
|
|
4
|
-
|
|
5
|
-
import type { AxiosInstance, AxiosRequestConfig, HeadersDefaults, ResponseType, AxiosResponse } from "axios";
|
|
6
|
-
import axios from "axios";
|
|
7
|
-
|
|
8
|
-
export type QueryParamsType = Record<string | number, any>;
|
|
9
|
-
|
|
10
|
-
<% if (config.param?.extractResponseRaw) { %>
|
|
11
|
-
/** 提取响应 */
|
|
12
|
-
export interface
|
|
13
|
-
/** 原始数据 */
|
|
14
|
-
raw:
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
<% } %>
|
|
18
|
-
export interface FullRequestParams extends Omit<AxiosRequestConfig, "data" | "params" | "url" | "responseType"> {
|
|
19
|
-
/** set parameter to `true` for call `securityWorker` for this request */
|
|
20
|
-
secure?: boolean;
|
|
21
|
-
/** request path */
|
|
22
|
-
path: string;
|
|
23
|
-
/** content type of request body */
|
|
24
|
-
type?: ContentType;
|
|
25
|
-
/** query params */
|
|
26
|
-
query?: QueryParamsType;
|
|
27
|
-
/** format of response (i.e. response.json() -> format: "json") */
|
|
28
|
-
format?: ResponseType;
|
|
29
|
-
/** request body */
|
|
30
|
-
body?: unknown;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
|
|
34
|
-
|
|
35
|
-
export interface ApiConfig<SecurityDataType = unknown> extends Omit<AxiosRequestConfig, "data" | "cancelToken"> {
|
|
36
|
-
securityWorker?: (securityData: SecurityDataType | null) => Promise<AxiosRequestConfig | void> | AxiosRequestConfig | void;
|
|
37
|
-
secure?: boolean;
|
|
38
|
-
format?: ResponseType;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export enum ContentType {
|
|
42
|
-
Json = "application/json",
|
|
43
|
-
JsonApi = "application/vnd.api+json",
|
|
44
|
-
FormData = "multipart/form-data",
|
|
45
|
-
UrlEncoded = "application/x-www-form-urlencoded",
|
|
46
|
-
Text = "text/plain",
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export class HttpClient<SecurityDataType = unknown> {
|
|
50
|
-
public instance: AxiosInstance;
|
|
51
|
-
private securityData: SecurityDataType | null = null;
|
|
52
|
-
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
|
|
53
|
-
private secure?: boolean;
|
|
54
|
-
private format?: ResponseType;
|
|
55
|
-
|
|
56
|
-
constructor({ securityWorker, secure, format, ...axiosConfig }: ApiConfig<SecurityDataType> = {}) {
|
|
57
|
-
this.instance = axios.create({ ...axiosConfig, baseURL: axiosConfig.baseURL || "<%~ apiConfig.baseUrl %>" })
|
|
58
|
-
this.secure = secure;
|
|
59
|
-
this.format = format;
|
|
60
|
-
this.securityWorker = securityWorker;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
public setSecurityData = (data: SecurityDataType | null) => {
|
|
64
|
-
this.securityData = data
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
protected mergeRequestParams(params1: AxiosRequestConfig, params2?: AxiosRequestConfig): AxiosRequestConfig {
|
|
68
|
-
const method = params1.method || (params2 && params2.method)
|
|
69
|
-
|
|
70
|
-
return {
|
|
71
|
-
...this.instance.defaults,
|
|
72
|
-
...params1,
|
|
73
|
-
...(params2 || {}),
|
|
74
|
-
headers: {
|
|
75
|
-
...((method && this.instance.defaults.headers[method.toLowerCase() as keyof HeadersDefaults]) || {}),
|
|
76
|
-
...(params1.headers || {}),
|
|
77
|
-
...((params2 && params2.headers) || {}),
|
|
78
|
-
},
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
protected stringifyFormItem(formItem: unknown) {
|
|
83
|
-
if (typeof formItem === "object" && formItem !== null) {
|
|
84
|
-
return JSON.stringify(formItem);
|
|
85
|
-
} else {
|
|
86
|
-
return `${formItem}`;
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
protected createFormData(input: Record<string, unknown>): FormData {
|
|
91
|
-
if (input instanceof FormData) {
|
|
92
|
-
return input;
|
|
93
|
-
}
|
|
94
|
-
return Object.keys(input || {}).reduce((formData, key) => {
|
|
95
|
-
const property = input[key];
|
|
96
|
-
const propertyContent: any[] = (property instanceof Array) ? property : [property]
|
|
97
|
-
|
|
98
|
-
for (const formItem of propertyContent) {
|
|
99
|
-
const isFileType = formItem instanceof Blob || formItem instanceof File;
|
|
100
|
-
formData.append(
|
|
101
|
-
key,
|
|
102
|
-
isFileType ? formItem : this.stringifyFormItem(formItem)
|
|
103
|
-
);
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
return formData;
|
|
107
|
-
}, new FormData());
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
public request = async <T = any, _E = any>({
|
|
111
|
-
secure,
|
|
112
|
-
path,
|
|
113
|
-
type,
|
|
114
|
-
query,
|
|
115
|
-
format,
|
|
116
|
-
body,
|
|
117
|
-
...params
|
|
118
|
-
<% if (config.unwrapResponseData) { %>
|
|
119
|
-
}: FullRequestParams): Promise<T> => {
|
|
120
|
-
<% } else
|
|
121
|
-
}: FullRequestParams): Promise<
|
|
122
|
-
<% }
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
<%
|
|
148
|
-
})
|
|
149
|
-
<% }
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
});
|
|
153
|
-
<% } %>
|
|
154
|
-
};
|
|
155
|
-
}
|
|
1
|
+
<%
|
|
2
|
+
const { apiConfig, generateResponses, config } = it;
|
|
3
|
+
%>
|
|
4
|
+
|
|
5
|
+
import type { AxiosInstance, AxiosRequestConfig, HeadersDefaults, ResponseType, AxiosResponse as AxiosResponseRaw } from "axios";
|
|
6
|
+
import axios from "axios";
|
|
7
|
+
|
|
8
|
+
export type QueryParamsType = Record<string | number, any>;
|
|
9
|
+
|
|
10
|
+
<% if (config.param?.extractResponseRaw) { %>
|
|
11
|
+
/** 提取响应 */
|
|
12
|
+
export interface AxiosResponse<T = any> {
|
|
13
|
+
/** 原始数据 */
|
|
14
|
+
raw: AxiosResponseRaw<T>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
<% } %>
|
|
18
|
+
export interface FullRequestParams extends Omit<AxiosRequestConfig, "data" | "params" | "url" | "responseType"> {
|
|
19
|
+
/** set parameter to `true` for call `securityWorker` for this request */
|
|
20
|
+
secure?: boolean;
|
|
21
|
+
/** request path */
|
|
22
|
+
path: string;
|
|
23
|
+
/** content type of request body */
|
|
24
|
+
type?: ContentType;
|
|
25
|
+
/** query params */
|
|
26
|
+
query?: QueryParamsType;
|
|
27
|
+
/** format of response (i.e. response.json() -> format: "json") */
|
|
28
|
+
format?: ResponseType;
|
|
29
|
+
/** request body */
|
|
30
|
+
body?: unknown;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type RequestParams = Omit<FullRequestParams, "body" | "method" | "query" | "path">;
|
|
34
|
+
|
|
35
|
+
export interface ApiConfig<SecurityDataType = unknown> extends Omit<AxiosRequestConfig, "data" | "cancelToken"> {
|
|
36
|
+
securityWorker?: (securityData: SecurityDataType | null) => Promise<AxiosRequestConfig | void> | AxiosRequestConfig | void;
|
|
37
|
+
secure?: boolean;
|
|
38
|
+
format?: ResponseType;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export enum ContentType {
|
|
42
|
+
Json = "application/json",
|
|
43
|
+
JsonApi = "application/vnd.api+json",
|
|
44
|
+
FormData = "multipart/form-data",
|
|
45
|
+
UrlEncoded = "application/x-www-form-urlencoded",
|
|
46
|
+
Text = "text/plain",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class HttpClient<SecurityDataType = unknown> {
|
|
50
|
+
public instance: AxiosInstance;
|
|
51
|
+
private securityData: SecurityDataType | null = null;
|
|
52
|
+
private securityWorker?: ApiConfig<SecurityDataType>["securityWorker"];
|
|
53
|
+
private secure?: boolean;
|
|
54
|
+
private format?: ResponseType;
|
|
55
|
+
|
|
56
|
+
constructor({ securityWorker, secure, format, ...axiosConfig }: ApiConfig<SecurityDataType> = {}) {
|
|
57
|
+
this.instance = axios.create({ ...axiosConfig, baseURL: axiosConfig.baseURL || "<%~ apiConfig.baseUrl %>" })
|
|
58
|
+
this.secure = secure;
|
|
59
|
+
this.format = format;
|
|
60
|
+
this.securityWorker = securityWorker;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
public setSecurityData = (data: SecurityDataType | null) => {
|
|
64
|
+
this.securityData = data
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
protected mergeRequestParams(params1: AxiosRequestConfig, params2?: AxiosRequestConfig): AxiosRequestConfig {
|
|
68
|
+
const method = params1.method || (params2 && params2.method)
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
...this.instance.defaults,
|
|
72
|
+
...params1,
|
|
73
|
+
...(params2 || {}),
|
|
74
|
+
headers: {
|
|
75
|
+
...((method && this.instance.defaults.headers[method.toLowerCase() as keyof HeadersDefaults]) || {}),
|
|
76
|
+
...(params1.headers || {}),
|
|
77
|
+
...((params2 && params2.headers) || {}),
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
protected stringifyFormItem(formItem: unknown) {
|
|
83
|
+
if (typeof formItem === "object" && formItem !== null) {
|
|
84
|
+
return JSON.stringify(formItem);
|
|
85
|
+
} else {
|
|
86
|
+
return `${formItem}`;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
protected createFormData(input: Record<string, unknown>): FormData {
|
|
91
|
+
if (input instanceof FormData) {
|
|
92
|
+
return input;
|
|
93
|
+
}
|
|
94
|
+
return Object.keys(input || {}).reduce((formData, key) => {
|
|
95
|
+
const property = input[key];
|
|
96
|
+
const propertyContent: any[] = (property instanceof Array) ? property : [property]
|
|
97
|
+
|
|
98
|
+
for (const formItem of propertyContent) {
|
|
99
|
+
const isFileType = formItem instanceof Blob || formItem instanceof File;
|
|
100
|
+
formData.append(
|
|
101
|
+
key,
|
|
102
|
+
isFileType ? formItem : this.stringifyFormItem(formItem)
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return formData;
|
|
107
|
+
}, new FormData());
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
public request = async <T = any, _E = any>({
|
|
111
|
+
secure,
|
|
112
|
+
path,
|
|
113
|
+
type,
|
|
114
|
+
query,
|
|
115
|
+
format,
|
|
116
|
+
body,
|
|
117
|
+
...params
|
|
118
|
+
<% if (config.unwrapResponseData) { %>
|
|
119
|
+
}: FullRequestParams): Promise<T> => {
|
|
120
|
+
<% } else { %>
|
|
121
|
+
}: FullRequestParams): Promise<AxiosResponse<T>> => {
|
|
122
|
+
<% } %>
|
|
123
|
+
const secureParams = ((typeof secure === 'boolean' ? secure : this.secure) && this.securityWorker && (await this.securityWorker(this.securityData))) || {};
|
|
124
|
+
const requestParams = this.mergeRequestParams(params, secureParams);
|
|
125
|
+
const responseFormat = (format || this.format) || undefined;
|
|
126
|
+
|
|
127
|
+
if (type === ContentType.FormData && body && body !== null && typeof body === "object") {
|
|
128
|
+
body = this.createFormData(body as Record<string, unknown>);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (type === ContentType.Text && body && body !== null && typeof body !== "string") {
|
|
132
|
+
body = JSON.stringify(body);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return this.instance.request({
|
|
136
|
+
...requestParams,
|
|
137
|
+
headers: {
|
|
138
|
+
...(requestParams.headers || {}),
|
|
139
|
+
...(type ? { "Content-Type": type } : {}),
|
|
140
|
+
},
|
|
141
|
+
params: query,
|
|
142
|
+
responseType: responseFormat,
|
|
143
|
+
data: body,
|
|
144
|
+
url: path,
|
|
145
|
+
<% if (config.unwrapResponseData) { %>
|
|
146
|
+
}).then(response => response.data);
|
|
147
|
+
<% } else { %>
|
|
148
|
+
});
|
|
149
|
+
<% } %>
|
|
150
|
+
};
|
|
151
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fxri/swagger2api",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.9",
|
|
4
4
|
"description": "基于 swagger-typescript-api,将 Swagger 文档自动转为 TypeScript 格式的 API 文件。",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"@types/prompts": "^2.4.9",
|
|
33
33
|
"@typescript-eslint/eslint-plugin": "^6.21.0",
|
|
34
34
|
"@typescript-eslint/parser": "^6.21.0",
|
|
35
|
+
"cross-env": "^10.1.0",
|
|
35
36
|
"esbuild-plugin-copy": "^2.1.1",
|
|
36
37
|
"eslint": "^8.57.1",
|
|
37
38
|
"eslint-config-prettier": "^9.1.2",
|
|
@@ -55,9 +56,9 @@
|
|
|
55
56
|
},
|
|
56
57
|
"scripts": {
|
|
57
58
|
"dev": "pnpm build:debug && node ./dist/cli.js",
|
|
58
|
-
"build": "NODE_ENV=production tsup",
|
|
59
|
-
"build:debug": "NODE_ENV=development tsup --config tsup.dev.config.ts",
|
|
59
|
+
"build": "cross-env NODE_ENV=production tsup",
|
|
60
|
+
"build:debug": "cross-env NODE_ENV=development tsup --config tsup.dev.config.ts",
|
|
60
61
|
"release": "pnpm build && pnpm publish",
|
|
61
|
-
"api": "pnpm dev --axios --responses
|
|
62
|
+
"api": "pnpm dev --axios --responses -q -rpi 0 -err"
|
|
62
63
|
}
|
|
63
64
|
}
|