@fxri/swagger2api 1.1.8 → 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 +12 -2
- 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/route-types.ejs +32 -32
- package/dist/templates/type-data-contract.ejs +15 -15
- package/package.json +2 -2
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
|
```
|
|
@@ -153,6 +153,7 @@ client.instance.interceptors.response.use(
|
|
|
153
153
|
| `--config,-c` | string | `'saconfig.json'` | 填写配置文件路径,支持多选,用【,】分隔 |
|
|
154
154
|
| `--config-all,-ca` | boolean | `false` | 加载全部配置文件,不进行选择 |
|
|
155
155
|
| `--config-scan,-cs` | boolean | `true` | 扫描全部配置文件,并提供选择列表 |
|
|
156
|
+
| `--replace-tags,-rt` | string[] | - | 替换标签,2个参数,第1个正则表达式(已包含^$头尾),第2个替换字符串 |
|
|
156
157
|
| `--convert-get,-cg` | boolean | `false` | 转换无{.+}get为query |
|
|
157
158
|
| `--remove-param,-rp` | boolean | `false` | 移除{.+}参数 |
|
|
158
159
|
| `--remove-prefix-index,-rpi` | number | `-1` | 移除前缀索引 |
|
|
@@ -178,6 +179,7 @@ npx @fxri/swagger2api [--quick,-q] [--quick,-q <boolean>]
|
|
|
178
179
|
npx swagger2api [--config,-c <path>]
|
|
179
180
|
|
|
180
181
|
npx @fxri/swagger2api [--config,-c <path>]
|
|
182
|
+
```
|
|
181
183
|
|
|
182
184
|
```bash
|
|
183
185
|
# 移除前缀索引
|
|
@@ -187,6 +189,14 @@ npx swagger2api [--remove-prefix-index,-rpi <number>]
|
|
|
187
189
|
npx @fxri/swagger2api [--remove-prefix-index,-rpi <number>]
|
|
188
190
|
```
|
|
189
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
|
+
|
|
190
200
|
## 🤝 贡献
|
|
191
201
|
|
|
192
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};
|
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
<%
|
|
2
|
-
const { utils, config, routes, modelTypes } = it;
|
|
3
|
-
const { _, pascalCase } = utils;
|
|
4
|
-
const dataContracts = config.modular ? _.map(modelTypes, "name") : [];
|
|
5
|
-
%>
|
|
6
|
-
|
|
7
|
-
<% if (dataContracts.length) { %>
|
|
8
|
-
import { <%~ dataContracts.join(", ") %> } from "./<%~ config.fileNames.dataContracts %>"
|
|
9
|
-
<% } %>
|
|
10
|
-
|
|
11
|
-
<%
|
|
12
|
-
/* TODO: outOfModule, combined should be attributes of route, which will allow to avoid duplication of code */
|
|
13
|
-
%>
|
|
14
|
-
|
|
15
|
-
<% if (routes.outOfModule) { %>
|
|
16
|
-
<% for (const { routes: outOfModuleRoutes = [] } of routes.outOfModule) { %>
|
|
17
|
-
<% for (const route of outOfModuleRoutes) { %>
|
|
18
|
-
<%~ includeFile('./route-type.ejs', { ...it, route }) %>
|
|
19
|
-
<% } %>
|
|
20
|
-
<% } %>
|
|
21
|
-
<% } %>
|
|
22
|
-
|
|
23
|
-
<% if (routes.combined) { %>
|
|
24
|
-
<% for (const { routes: combinedRoutes = [], moduleName } of routes.combined) { %>
|
|
25
|
-
export namespace <%~ pascalCase(moduleName) %> {
|
|
26
|
-
<% for (const route of combinedRoutes) { %>
|
|
27
|
-
<%~ includeFile('./route-type.ejs', { ...it, route }) %>
|
|
28
|
-
<% } %>
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
<% } %>
|
|
32
|
-
<% } %>
|
|
1
|
+
<%
|
|
2
|
+
const { utils, config, routes, modelTypes } = it;
|
|
3
|
+
const { _, pascalCase } = utils;
|
|
4
|
+
const dataContracts = config.modular ? _.map(modelTypes, "name") : [];
|
|
5
|
+
%>
|
|
6
|
+
|
|
7
|
+
<% if (dataContracts.length) { %>
|
|
8
|
+
import { <%~ dataContracts.join(", ") %> } from "./<%~ config.fileNames.dataContracts %>"
|
|
9
|
+
<% } %>
|
|
10
|
+
|
|
11
|
+
<%
|
|
12
|
+
/* TODO: outOfModule, combined should be attributes of route, which will allow to avoid duplication of code */
|
|
13
|
+
%>
|
|
14
|
+
|
|
15
|
+
<% if (routes.outOfModule) { %>
|
|
16
|
+
<% for (const { routes: outOfModuleRoutes = [] } of routes.outOfModule) { %>
|
|
17
|
+
<% for (const route of outOfModuleRoutes) { %>
|
|
18
|
+
<%~ includeFile('./route-type.ejs', { ...it, route }) %>
|
|
19
|
+
<% } %>
|
|
20
|
+
<% } %>
|
|
21
|
+
<% } %>
|
|
22
|
+
|
|
23
|
+
<% if (routes.combined) { %>
|
|
24
|
+
<% for (const { routes: combinedRoutes = [], moduleName } of routes.combined) { %>
|
|
25
|
+
export namespace <%~ pascalCase(moduleName) %> {
|
|
26
|
+
<% for (const route of combinedRoutes) { %>
|
|
27
|
+
<%~ includeFile('./route-type.ejs', { ...it, route }) %>
|
|
28
|
+
<% } %>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
<% } %>
|
|
32
|
+
<% } %>
|
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
<%
|
|
2
|
-
const { contract, utils } = it;
|
|
3
|
-
const { formatDescription, require, _ } = utils;
|
|
4
|
-
|
|
5
|
-
%>
|
|
6
|
-
<% if (contract.$content.length) { %>
|
|
7
|
-
export type <%~ contract.name %> = {
|
|
8
|
-
<% for (const field of contract.$content) { %>
|
|
9
|
-
<%~ includeFile('./object-field-jsdoc.ejs', { ...it, field }) %>
|
|
10
|
-
<%~ field.field %>;
|
|
11
|
-
<% } %>
|
|
12
|
-
}<%~ utils.isNeedToAddNull(contract) ? ' | null' : ''%>
|
|
13
|
-
<% } else { %>
|
|
14
|
-
export type <%~ contract.name %> = Record<string, any>;
|
|
15
|
-
<% } %>
|
|
1
|
+
<%
|
|
2
|
+
const { contract, utils } = it;
|
|
3
|
+
const { formatDescription, require, _ } = utils;
|
|
4
|
+
|
|
5
|
+
%>
|
|
6
|
+
<% if (contract.$content.length) { %>
|
|
7
|
+
export type <%~ contract.name %> = {
|
|
8
|
+
<% for (const field of contract.$content) { %>
|
|
9
|
+
<%~ includeFile('./object-field-jsdoc.ejs', { ...it, field }) %>
|
|
10
|
+
<%~ field.field %>;
|
|
11
|
+
<% } %>
|
|
12
|
+
}<%~ utils.isNeedToAddNull(contract) ? ' | null' : ''%>
|
|
13
|
+
<% } else { %>
|
|
14
|
+
export type <%~ contract.name %> = Record<string, any>;
|
|
15
|
+
<% } %>
|
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": {
|
|
@@ -59,6 +59,6 @@
|
|
|
59
59
|
"build": "cross-env NODE_ENV=production tsup",
|
|
60
60
|
"build:debug": "cross-env NODE_ENV=development tsup --config tsup.dev.config.ts",
|
|
61
61
|
"release": "pnpm build && pnpm publish",
|
|
62
|
-
"api": "pnpm dev --axios --responses
|
|
62
|
+
"api": "pnpm dev --axios --responses -q -rpi 0 -err"
|
|
63
63
|
}
|
|
64
64
|
}
|