sy-api-pro 1.0.5 → 1.0.7
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/dist/index.umd.js +1 -1
- package/package.json +3 -3
- package/template/api/axios.ts +9 -10
package/dist/index.umd.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
(function(w,q){typeof exports=="object"&&typeof module!="undefined"?q(require("axios")):typeof define=="function"&&define.amd?define(["axios"],q):(w=typeof globalThis!="undefined"?globalThis:w||self,q(w.axios))})(this,function(w){"use strict";var v=(w,q,B)=>new Promise((A,s)=>{var d=g=>{try{N(B.next(g))}catch(I){s(I)}},c=g=>{try{N(B.throw(g))}catch(I){s(I)}},N=g=>g.done?A(g.value):Promise.resolve(g.value).then(d,c);N((B=B.apply(w,q)).next())});const q=a=>{var h;const t=(a||"").toLowerCase(),o={int:"number",integer:"number",long:"number",bigdecimal:"number",float:"number",double:"number",localdatetime:"string",date:"string",char:"string",byte:"string",short:"string",character:"string",string:"string",multipartfile:"string",boolean:"boolean",void:"void"},{listType:l}=((h=new RegExp("^list<(?<listType>.+)>$").exec(t))==null?void 0:h.groups)||{};return l?`Array<${o[l]||"any"}>`:o[t]||"any"},B=require("chalk"),A=Object.freeze({_getDesc(a){const t=(a.title||"").trim();return t?` // ${t}`:""},getInterface:function({list:a,config:{ignoreParamsDTO:t,deleteParentDTO:o}}){const l=a.map((n,i)=>n.level===0?i:null).filter(n=>n!==null);return(l.length>0?l.concat(a.length).map((n,i,e)=>a.slice(n,e[i+1])):[a]).filter(n=>n.length).filter(n=>!t.includes(n[0].type)).map(n=>{const i=n[0];if(i.json){const e=i.json.split(`
|
|
2
2
|
`);return e.forEach((p,y)=>{var r;const _=new RegExp('(?<space>\\s*)"(?<name>[a-zA-Z0-9]+)"\\s?:\\s*"(?<desc>[\\S\\s]*)"\\s*,?\\s*$');if(_.test(p)){const{space:b,name:$,desc:F}=((r=_.exec(p))==null?void 0:r.groups)||{},j=($||"").trim(),P=(F||"").trim(),z=n.filter(R=>{const M=(R.name||"").trim()+(R.title||"").trim();return JSON.stringify(M).replace(/^"([\s\S]+)"$/,"$1")===j+P});if(z.length>=1){const[{type:R}]=z,M=i.required?"?":"",L=P?` // ${P}`:"";e[y]=`${b+j+M}: ${q(R)};${L}`}else console.log(B.yellowBright(`【warning】${j} 的类型错误,请手动处理`))}else e[y]=e[y].replace(/(\s*)"([a-zA-Z0-9]+)"\s?(:\s*[\S\s]+)$/,"$1$2$3").replace(/([\S\s]*)\[\s+{$/,"$1Array<{").replace(/([\S\s]*)}\s*][\S\s]*$/,"$1}>;")}),o.some(p=>{const y=Object.prototype.toString.call(p);if(y==="[object RegExp]")return p.test(i.type);if(y==="[object String]")return p===i.type})?e.slice(1,-1).join(`
|
|
3
3
|
`):[` ${i.name}${i.required?"":"?"}: {${this._getDesc(i)}`,...e.slice(1,-1).map(p=>` ${p}`)," };"].join(`
|
|
4
|
-
`)}else return` ${i.name}${i.required?"":"?"}: ${q(i.type)};${this._getDesc(i)}`})}}),s=require("fs"),d=require("path"),c=require("chalk");w.interceptors.response.use(a=>{var t,o;return(o=(t=a.data)==null?void 0:t.head)!=null&&o.successful?a:Promise.reject(a)},a=>{throw a});const N=class{constructor(t){this.config={api:"",customMethodName:"",projectId:void 0,branchId:void 0,methodId:void 0,outputPath:"",outputDirName:"",apiBaseName:"",ignoreParamsDTO:[],deleteParentDTO:[],apiHeaderTemplate:[]},this.apiList=[],this.enums=[],Object.assign(this.config,t),this.getApiData()}getApiData(){return v(this,null,function*(){const{api:t,branchId:o,projectId:l,outputDirName:h,outputPath:n,methodId:i}=this.config;try{const{data:e}=yield w.get(`${t}/api/project/getProjectWithBranchById?id=${l}`);this.config.outputPath=d.join(process.cwd(),n,h||e.body.name);const m=e.body.branchList.find(y=>y.id===o);if(m)console.log(c.blueBright(`【info】正在使用 branchName: ${m.name} branchId: ${o} methodId: ${i}`));else throw c.red(`【error】branchId ${o} 不存在`);const p=yield w.get(`${t}/api/method/getMethodById?id=${i}`);this.apiList=[p.data.body]}catch(e){console.log(c.red("【error】: 接口获取异常")),console.log(e);return}try{yield this.checkApiOutputDir()}catch(e){console.log(c.red("【error】: 检查输出目录异常")),console.log(e);return}try{yield this.createFile()}catch(e){console.log(c.red("【error】: createFile 异常")),console.log(e)}})}checkApiOutputDir(){const{outputPath:t}=this.config;console.log(c.blueBright(`【info】输出目录 ${t}`));try{s.statSync(t,{bigint:!0})}catch(o){s.mkdirSync(t,{recursive:!0})}}creatBaseFile(){return v(this,null,function*(){const{outputPath:t}=this.config,o=d.join(__dirname,"../template/api"),l=s.readdirSync(o),h=s.readdirSync(t);for(const n of l)if(!h.includes(n))try{const i=s.readFileSync(d.join(o,n));s.writeFileSync(d.join(t,n),i)}catch(i){console.log(c.red("【error】: 基础文件生成异常")),console.log(i)}})}createFile(){return v(this,null,function*(){var h,n,i;const{apiBaseName:t,outputPath:o,customMethodName:l}=this.config;for(const e of this.apiList){const m=u=>u.replace(/(-[a-z])|(^[a-z])/g,f=>f.replace("-","").toLocaleUpperCase()),p=e.path.startsWith("/")?e.path:`/${e.path}`,y=typeof t=="string"?t.startsWith("/")?t:`/${t}`:t,_=p.replace(y,""),{apiDirName:r}=((h=new RegExp("(/)?(?<apiDirName>[a-zA-Z0-9_]+)/.*$").exec(_))==null?void 0:h.groups)||{},b=l||e.name,$=m(`${r}-`+b);try{s.statSync(d.join(o,r)).isDirectory()}catch(u){s.mkdirSync(d.join(o,r))}let F="";try{F=s.readFileSync(d.join(o,r,"models.ts")).toString()}catch(u){s.writeFileSync(d.join(o,`./${r}/models.ts`),"")}let j=[],P=[];try{const u=A.getInterface({list:e.paramList||[],config:this.config});j=(n=e.paramList)!=null&&n.length&&u.length?[F?"":"/* ************************************************ */",`/** ${e.title} RequestModel */`,`export interface ${$}ReqModel {`,...u,"}",""]:[];const f=A.getInterface({list:e.returnList||[],config:this.config});P=(i=e.returnList)!=null&&i.length&&f.length?[j.length?"":"/* ************************************************ */",`/** ${e.title} ResponseModel */`,`export interface ${$}ResModel {`,...f,"}",""]:[]}catch(u){throw console.log(c.red(`【error】类型生成失败 projectId: ${this.config.projectId} methodId: ${e.id} path: ${p}`)),c.red(u)}F.includes(`export interface ${$}ReqModel {`)?console.log(c.yellowBright(`【warning】./${r}/models.ts 已存在 ${$}ReqModel`)):j.length&&(s.appendFileSync(d.join(o,`./${r}/models.ts`),j.join(`
|
|
4
|
+
`)}else return` ${i.name}${i.required?"":"?"}: ${q(i.type)};${this._getDesc(i)}`})}}),s=require("fs"),d=require("path"),c=require("chalk");w.interceptors.response.use(a=>{var t,o;return(o=(t=a.data)==null?void 0:t.head)!=null&&o.successful?a:Promise.reject(a)},a=>{throw a});const N=class{constructor(t){this.config={api:"",customMethodName:"",projectId:void 0,branchId:void 0,methodId:void 0,outputPath:"",outputDirName:"",apiBaseName:"",ignoreParamsDTO:[],deleteParentDTO:[],apiHeaderTemplate:[]},this.apiList=[],this.enums=[],Object.assign(this.config,t),this.getApiData()}getApiData(){return v(this,null,function*(){const{api:t,branchId:o,projectId:l,outputDirName:h,outputPath:n,methodId:i}=this.config;try{const{data:e}=yield w.get(`${t}/api/project/getProjectWithBranchById?id=${l}`);this.config.outputPath=d.join(process.cwd(),n,h||e.body.name);const m=e.body.branchList.find(y=>y.id===o);if(m)console.log(c.blueBright(`【info】正在使用 branchName: ${m.name} branchId: ${o} methodId: ${i}`));else throw c.red(`【error】branchId ${o} 不存在`);const p=yield w.get(`${t}/api/method/getMethodById?id=${i}`);this.apiList=[p.data.body]}catch(e){console.log(c.red("【error】: 接口获取异常")),console.log(e);return}try{yield this.checkApiOutputDir()}catch(e){console.log(c.red("【error】: 检查输出目录异常")),console.log(e);return}try{yield this.createFile()}catch(e){console.log(c.red("【error】: createFile 异常")),console.log(e)}})}checkApiOutputDir(){const{outputPath:t}=this.config;console.log(c.blueBright(`【info】输出目录 ${t}`));try{s.statSync(t,{bigint:!0})}catch(o){s.mkdirSync(t,{recursive:!0})}}creatBaseFile(){return v(this,null,function*(){const{outputPath:t}=this.config,o=d.join(__dirname,"../template/api"),l=s.readdirSync(o),h=s.readdirSync(t);for(const n of l)if(!h.includes(n))try{const i=s.readFileSync(d.join(o,n));s.writeFileSync(d.join(t,n),i)}catch(i){console.log(c.red("【error】: 基础文件生成异常")),console.log(i)}})}createFile(){return v(this,null,function*(){var h,n,i;const{apiBaseName:t,outputPath:o,customMethodName:l}=this.config;for(const e of this.apiList){const m=u=>u.replace(/(-[a-z])|(^[a-z])/g,f=>f.replace("-","").toLocaleUpperCase()),p=e.path.startsWith("/")?e.path:`/${e.path}`,y=typeof t=="string"?t.startsWith("/")?t:`/${t}`:t,_=p.replace(y,""),{apiDirName:r}=((h=new RegExp("(/)?(?<apiDirName>[a-zA-Z0-9_-]+)/.*$").exec(_))==null?void 0:h.groups)||{},b=l||e.name,$=m(`${r}-`+b);try{s.statSync(d.join(o,r)).isDirectory()}catch(u){s.mkdirSync(d.join(o,r))}let F="";try{F=s.readFileSync(d.join(o,r,"models.ts")).toString()}catch(u){s.writeFileSync(d.join(o,`./${r}/models.ts`),"")}let j=[],P=[];try{const u=A.getInterface({list:e.paramList||[],config:this.config});j=(n=e.paramList)!=null&&n.length&&u.length?[F?"":"/* ************************************************ */",`/** ${e.title} RequestModel */`,`export interface ${$}ReqModel {`,...u,"}",""]:[];const f=A.getInterface({list:e.returnList||[],config:this.config});P=(i=e.returnList)!=null&&i.length&&f.length?[j.length?"":"/* ************************************************ */",`/** ${e.title} ResponseModel */`,`export interface ${$}ResModel {`,...f,"}",""]:[]}catch(u){throw console.log(c.red(`【error】类型生成失败 projectId: ${this.config.projectId} methodId: ${e.id} path: ${p}`)),c.red(u)}F.includes(`export interface ${$}ReqModel {`)?console.log(c.yellowBright(`【warning】./${r}/models.ts 已存在 ${$}ReqModel`)):j.length&&(s.appendFileSync(d.join(o,`./${r}/models.ts`),j.join(`
|
|
5
5
|
`)),console.log(c.greenBright(`【success】./${r}/models.ts 成功添加 ${$}ReqModel`))),F.includes(`export interface ${$}ResModel {`)?console.log(c.yellowBright(`【warning】./${r}/models.ts 已存在 ${$}ResModel`)):P.length&&(s.appendFileSync(d.join(o,`./${r}/models.ts`),P.join(`
|
|
6
6
|
`)),console.log(c.greenBright(`【success】./${r}/models.ts 成功添加 ${$}ResModel`)));const M=[e.title&&` /** ${e.title} */`,` ${b}(${j.length?`params: M.${$}ReqModel`:""}) {`,` return axios.${e.method.toLowerCase()}<ApiResponse<${P.length?`M.${$}ResModel`:"any"}>>(`,` \`\${ApiPrefix}${p}\`,`,j.length&&` ${["post","put","patch"].includes(e.method.toLowerCase())?"params":"{ params }"},`," );"," },"].filter(Boolean);/^[a-zA-Z]+$/.test((e.method||"").trim())||console.log(c.yellowBright(`【warning】接口请求类型异常,请手动补全 method:${e.method} path: ${p} methodId: ${this.config.methodId} projectId: ${this.config.projectId}`));const L=`${m(r)}Api`;try{const u=s.readFileSync(d.join(o,r,"api.ts")).toString(),f=u.split(`
|
|
7
7
|
`);if(!u.includes("import"))throw Error("null");if(u.includes(` ${b}(`)){const S=f.findIndex(x=>x.includes(` ${b}(`)),T=f.findIndex((x,k)=>k>S&&x===" },");console.log(c.yellowBright([`【warning】./${r}/api.ts 已存在api`,...f.slice(S,T+1).map(x=>` ${x}`)].join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "sy-api-pro",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.7",
|
|
4
4
|
"main": "./bin/index.ts",
|
|
5
5
|
"types": "./bin/model.d.ts",
|
|
6
6
|
"bin": {
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
"dependencies": {
|
|
35
35
|
"@types/node": "^20.12.12",
|
|
36
36
|
"axios": "^1.6.8",
|
|
37
|
-
"chalk": "
|
|
38
|
-
"commander": "
|
|
37
|
+
"chalk": "4.1.2",
|
|
38
|
+
"commander": "11.1.0",
|
|
39
39
|
"ts-node": "^10.9.2",
|
|
40
40
|
"typescript": "^5.4.5"
|
|
41
41
|
},
|
package/template/api/axios.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import Axios, { AxiosResponse } from 'axios';
|
|
2
2
|
|
|
3
|
-
import { ApiPrefix } from './apiPrefix';
|
|
4
|
-
|
|
5
3
|
export interface ApiResponse<T> {
|
|
6
4
|
// success: boolean;
|
|
7
5
|
// message: string;
|
|
@@ -15,16 +13,17 @@ export const axios = Axios.create({
|
|
|
15
13
|
});
|
|
16
14
|
|
|
17
15
|
axios.interceptors.request.use((config) => {
|
|
18
|
-
|
|
19
|
-
|
|
16
|
+
// ...
|
|
17
|
+
return config;
|
|
20
18
|
}, error => Promise.reject(error));
|
|
21
19
|
|
|
22
20
|
axios.interceptors.response.use((response: AxiosResponse) => {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
21
|
+
// if (response.data?.success) {
|
|
22
|
+
// return response;
|
|
23
|
+
// }
|
|
24
|
+
console.log(response.data);
|
|
25
|
+
return Promise.reject(response);
|
|
28
26
|
}, (error) => {
|
|
29
|
-
|
|
27
|
+
console.error(error);
|
|
28
|
+
return Promise.reject(error);
|
|
30
29
|
});
|