sy-api-pro 1.0.1 → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.umd.js +13 -13
- package/package.json +1 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
(function(y,
|
|
2
|
-
`);return
|
|
3
|
-
`):[` ${o.name}${o.required?"":"?"}: {${this._getDesc(o)}`,...
|
|
4
|
-
`)}else return` ${o.name}${o.required?"":"?"}: ${
|
|
5
|
-
`)),console.log(c.greenBright(`【success】./${e}/models.ts 成功添加 ${g}ReqModel`))),
|
|
6
|
-
`)),console.log(c.greenBright(`【success】./${e}/models.ts 成功添加 ${g}ResModel`)));const L=[t.title&&` /** ${t.title} */`,` ${
|
|
7
|
-
`);if(!u.includes("import"))throw Error("null");if(u.includes(` ${
|
|
8
|
-
`))),console.log(c.yellowBright(`【warning】当前需要生成的 path 为 ${o}, methodName 为 ${
|
|
9
|
-
`)),
|
|
10
|
-
`)),console.log(c.greenBright(`【success】./${e}/api.ts 成功添加 ${
|
|
11
|
-
`)),console.log(c.greenBright(`【success】./${e}/api.ts 成功添加 ${
|
|
12
|
-
`);
|
|
13
|
-
`))}}})})}},j=require("fs")
|
|
1
|
+
(function(y,b){typeof exports=="object"&&typeof module!="undefined"?b(require("axios")):typeof define=="function"&&define.amd?define(["axios"],b):(y=typeof globalThis!="undefined"?globalThis:y||self,b(y.axios))})(this,function(y){"use strict";var O=(y,b,x)=>new Promise((d,m)=>{var c=f=>{try{j(x.next(f))}catch(B){m(B)}},T=f=>{try{j(x.throw(f))}catch(B){m(B)}},j=f=>f.done?d(f.value):Promise.resolve(f.value).then(c,T);j((x=x.apply(y,b)).next())});const b=a=>{var t;const n=(a||"").toLowerCase(),i={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:h}=((t=new RegExp("^list<(?<listType>.+)>$").exec(n))==null?void 0:t.groups)||{};return h?`Array<${i[h]||"any"}>`:i[n]||"any"},x=Object.freeze({_getDesc(a){const n=(a.title||"").trim();return n?` // ${n}`:""},getInterface:function({list:a,config:{ignoreParamsDTO:n,deleteParentDTO:i}}){const h=a.map((r,o)=>r.level===0&&!n.includes(r.type)?o:null).filter(r=>r!==null);return(h.length>0?h.concat(a.length).map((r,o,l)=>a.slice(r,l[o+1])):[a]).filter(r=>r.length).map(r=>{const o=r[0];if(o.json){const l=o.json.split(`
|
|
2
|
+
`);return l.forEach((e,p)=>{var F;const g=new RegExp('(?<space>\\s*)"(?<name>[a-zA-Z0-9]+)"\\s?:\\s*"(?<desc>.*)".*$');if(g.test(e)){const{space:q,name:P,desc:_}=((F=g.exec(e))==null?void 0:F.groups)||{},v=(P||"").trim(),L=(_||"").trim(),M=a.filter(S=>(S.name||"").trim()+(S.title||"").trim()===v+L);if(M.length>=1){const[{type:S}]=M,R=o.required?"?":"",u=L?` // ${L}`:"";l[p]=e.replace(g,`${q+P+R}: ${b(S)};${u}`)}}/\s*"[a-zA-Z0-9]+"\s*:\s*.+$/.test(e)&&(l[p]=l[p].replace(/(\s*)"([a-zA-Z0-9]+)"\s?(:\s*.+)$/,"$1$2$3")),l[p]=l[p].replace(/(.*)\[\s+{$/,"$1Array<{").replace(/(.*)}\s*].*$/,"$1}>")}),i.some(e=>{const p=Object.prototype.toString.call(e);if(p==="[object RegExp]")return e.test(o.type);if(p==="[object String]")return e===o.type})?l.slice(1,-1).join(`
|
|
3
|
+
`):[` ${o.name}${o.required?"":"?"}: {${this._getDesc(o)}`,...l.slice(1,-1).map(e=>` ${e}`)," }"].join(`
|
|
4
|
+
`)}else return` ${o.name}${o.required?"":"?"}: ${b(o.type)};${this._getDesc(o)}`})}}),d=require("fs"),m=require("path"),c=require("chalk");y.interceptors.response.use(a=>{var n,i;return(i=(n=a.data)==null?void 0:n.head)!=null&&i.successful?a:Promise.reject(a)},a=>{throw a});const T=class{constructor(n){this.config={api:"",creatBaseFile:!0,customMethodName:"",projectId:void 0,branchId:void 0,methodId:void 0,outputPath:"",outputDirName:"",apiBaseName:"",ignoreParamsDTO:[],deleteParentDTO:[],apiHeaderTemplate:[]},this.apiList=[],this.enums=[],Object.assign(this.config,n),this.getApiData()}getApiData(){return O(this,null,function*(){const{api:n,branchId:i,projectId:h,outputDirName:t,outputPath:r,methodId:o,creatBaseFile:l}=this.config;try{const{data:s}=yield y.get(`${n}/api/project/getProjectWithBranchById?id=${h}`);this.config.outputPath=m.join(process.cwd(),r,t||s.body.name);const e=s.body.branchList.find(g=>g.id===i);if(e)console.log(c.blueBright(`【info】正在使用 branchName: ${e.name} branchId: ${i} methodId: ${o}`));else throw c.red(`【error】branchId ${i} 不存在`);const p=yield y.get(`${n}/api/method/getMethodById?id=${o}`);this.apiList=[p.data.body]}catch(s){console.log(c.red("【error】: 接口获取异常")),console.log(s);return}try{yield this.checkApiOutputDir()}catch(s){console.log(c.red("【error】: 检查输出目录异常")),console.log(s);return}l&&(yield this.creatBaseFile());try{yield this.createFile()}catch(s){console.log(c.red("【error】: createFile 异常")),console.log(s)}})}checkApiOutputDir(){const{outputPath:n}=this.config;console.log(c.blueBright(`【info】输出目录 ${n}`));try{d.statSync(n,{bigint:!0})}catch(i){d.mkdirSync(n,{recursive:!0})}}creatBaseFile(){return O(this,null,function*(){const{outputPath:n}=this.config,i=m.join(__dirname,"../template/api"),h=d.readdirSync(i),t=d.readdirSync(n);for(const r of h)if(!t.includes(r))try{const o=d.readFileSync(m.join(i,r));d.writeFileSync(m.join(n,r),o)}catch(o){console.log(c.red("【error】: 基础文件生成异常")),console.log(o)}})}createFile(){return O(this,null,function*(){const{apiBaseName:n,outputPath:i,customMethodName:h}=this.config;this.apiList.forEach(t=>{var M,S,R;const r=u=>u.replace(/(-[a-z])|(^[a-z])/g,$=>$.replace("-","").toLocaleUpperCase()),o=t.path.startsWith("/")?t.path:`/${t.path}`,l=n.startsWith("/")?n:`/${n}`,s=new RegExp(`(${l})?(/)?(?<apiDirName>[a-zA-Z0-9_]+)/.*$`),{apiDirName:e}=((M=s.exec(o))==null?void 0:M.groups)||{},p=h||t.name,g=r(`${e}-`+p);try{d.statSync(m.join(i,e)).isDirectory()}catch(u){d.mkdirSync(m.join(i,e))}let F="";try{F=d.readFileSync(m.join(i,e,"models.ts")).toString()}catch(u){d.writeFileSync(m.join(i,`./${e}/models.ts`),"")}let q=[],P=[];try{const u=x.getInterface({list:t.paramList||[],config:this.config});q=(S=t.paramList)!=null&&S.length&&u.length?[F?"":"/* ************************************************ */",`/** ${t.title} RequestModel */`,`export interface ${g}ReqModel {`,...u,"}",""]:[];const $=x.getInterface({list:t.returnList||[],config:this.config});P=(R=t.returnList)!=null&&R.length&&$.length?[q.length?"":"/* ************************************************ */",`/** ${t.title} ResponseModel */`,`export interface ${g}ResModel {`,...$,"}",""]:[]}catch(u){throw console.log(c.red(`【error】类型生成失败 projectId: ${this.config.projectId} methodId: ${t.id} path: ${o}`)),c.red(u)}F.includes(`export interface ${g}ReqModel {`)?console.log(c.yellowBright(`【warning】./${e}/models.ts 已存在 ${g}ReqModel`)):q.length&&(d.appendFileSync(m.join(i,`./${e}/models.ts`),q.join(`
|
|
5
|
+
`)),console.log(c.greenBright(`【success】./${e}/models.ts 成功添加 ${g}ReqModel`))),F.includes(`export interface ${g}ResModel {`)?console.log(c.yellowBright(`【warning】./${e}/models.ts 已存在 ${g}ResModel`)):P.length&&(d.appendFileSync(m.join(i,`./${e}/models.ts`),P.join(`
|
|
6
|
+
`)),console.log(c.greenBright(`【success】./${e}/models.ts 成功添加 ${g}ResModel`)));const L=[t.title&&` /** ${t.title} */`,` ${p}(${q.length?`params: M.${g}ReqModel`:""}) {`,` return axios.${t.method.toLowerCase()}<ApiResponse<${P.length?`M.${g}ResModel`:"any"}>>(`,` \`\${ApiPrefix}${o}\`,`,q.length&&` ${["post","put","patch"].includes(t.method.toLowerCase())?"params":"{ params }"},`," );"," },"].filter(Boolean);/^[a-zA-Z]+$/.test((t.method||"").trim())||console.log(c.yellowBright(`【warning】接口请求类型异常,请手动补全 method:${t.method} path: ${o} methodId: ${this.config.methodId} projectId: ${this.config.projectId}`));try{const u=d.readFileSync(m.join(i,e,"api.ts")).toString(),$=u.split(`
|
|
7
|
+
`);if(!u.includes("import"))throw Error("null");if(u.includes(` ${p}(`)){const w=$.findIndex(I=>I.includes(` ${p}(`)),A=$.findIndex((I,N)=>N>w&&I===" },");console.log(c.yellowBright([`【warning】./${e}/api.ts 已存在api`,...$.slice(w,A+1).map(I=>` ${I}`)].join(`
|
|
8
|
+
`))),console.log(c.yellowBright(`【warning】当前需要生成的 path 为 ${o}, methodName 为 ${p}`))}else $.splice($.map(w=>w.includes("}")).lastIndexOf(!0),0,L.join(`
|
|
9
|
+
`)),d.writeFileSync(m.join(i,`./${e}/api.ts`),$.join(`
|
|
10
|
+
`)),console.log(c.greenBright(`【success】./${e}/api.ts 成功添加 ${p}`))}catch(u){const $=["import { axios, ApiResponse } from '../axios';","","import * as M from './models';","import { ApiPrefix } from '../apiPrefix';","","export * from './models';"],{apiHeaderTemplate:w}=this.config;d.writeFileSync(m.join(i,`./${e}/api.ts`),[...w!=null&&w.length?w:$,"",`export const ${r(e)}Api = {`,...L,"};",""].join(`
|
|
11
|
+
`)),console.log(c.greenBright(`【success】./${e}/api.ts 成功添加 ${p}`));const A=d.readFileSync(m.join(i,"index.ts")).toString();if(!A.includes(`export * from './${e}/api'`)){const I=A.split(`
|
|
12
|
+
`);I.push(`export * from './${e}/api';`);const N=I.slice(1).filter(Boolean);N.sort((k,z)=>k.localeCompare(z)),d.writeFileSync(m.join(i,"index.ts"),[I[0]||"","",...N,""].join(`
|
|
13
|
+
`))}}})})}},j=require("fs"),f=require("path"),{program:B}=require("commander"),D=require("chalk");B.name("sy-api-pro").version(require(f.resolve(__dirname,"../package.json")).version),B.command("init").description("初始化配置文件").option("-p, --path <char>","","./src/apis").action((a,n,i)=>{const h=f.join(process.cwd(),a.path),t=f.join(h,".api-config.ts");try{if(j.existsSync(h)||j.mkdirSync(h),j.existsSync(t))return console.log(D.yellowBright(`【warning】: ${t} 配置文件已存在`));const r=j.readFileSync(f.join(__dirname,"../template/config/.api-config.ts"));j.writeFileSync(t,r),console.log(D.greenBright(`【success】: 配置文件已生成, 路径:${t}`))}catch(r){console.log(D.red("【error】: 配置文件生成异常")),console.log(r)}}),B.command("create").description("生成api文件及类型定义").requiredOption("-i, --id <id>","methodId").option("-n, --name <name>","customMethodName").requiredOption("--config <filePath>","configFilePath").requiredOption("--project-id <id>","projectId").action((a,n,i)=>{var e;const{id:h,name:t,config:r,projectId:o}=a;if(!h||!/^\d+$/.test(h))throw D.red("【error】请传入正确的 id");const l=require(f.resolve(process.cwd(),r)),s=(l.projects||[]).find(p=>+p.projectId==+o);if(s){if(!s.branchId)throw D.red("【error】请传入正确的 branchId");if(!l.api)throw D.red("【error】请传入正确的 api");new T({api:l.api,creatBaseFile:(e=s.creatBaseFile)!=null?e:!0,methodId:h,customMethodName:t,outputPath:l.outputPath||"./src/apis",projectId:s.projectId,branchId:+s.branchId,outputDirName:s.outputDirName||"",apiBaseName:s.apiBaseName||"",ignoreParamsDTO:s.ignoreParamsDTO||[],deleteParentDTO:s.deleteParentDTO||[],apiHeaderTemplate:l.apiHeaderTemplate||[]})}else console.log(D.red(`【error】config 配置文件中 projects 未包含传入的 projectId ${o}`))}),B.parse()});
|