sy-api-pro 0.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/README.md +32 -0
- package/bin/index.d.ts +13 -0
- package/bin/index.js +3 -0
- package/dist/index.umd.js +12 -0
- package/package.json +37 -0
- package/template/apiPrefix.ts +1 -0
- package/template/index.ts +1 -0
- package/template/interceptors.ts +18 -0
- package/template/responseModel.ts +7 -0
package/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# package.json
|
|
2
|
+
```json
|
|
3
|
+
{
|
|
4
|
+
"scripts": {
|
|
5
|
+
"api": "sy-api-pro --config ./apis/.api-config.ts --project-id 888"
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
```
|
|
9
|
+
使用:yarn api -i 12345678 或 yarn api --id 12345678
|
|
10
|
+
|
|
11
|
+
# 配置文件(./apis/.api-config.ts)
|
|
12
|
+
```typescript
|
|
13
|
+
import { ConfigModels } from 'sy-api-pro';
|
|
14
|
+
|
|
15
|
+
const config: ConfigModels = {
|
|
16
|
+
outputPath: null, // 路径相对工程根目录【默认:'./src/apis'】
|
|
17
|
+
api: 'http://xxx.com', //
|
|
18
|
+
projects: [
|
|
19
|
+
{
|
|
20
|
+
projectId: null, // apidocs, url的 projectId 部分
|
|
21
|
+
branchId: null, // apidocs, url的 branchId 部分(与 scripts 中 --project-id 必须一致)
|
|
22
|
+
outputDirName: '', // 默认为获取到的appName
|
|
23
|
+
apiBaseName: '', //
|
|
24
|
+
creatBaseFile: true, // 生成基础文件 默认 true
|
|
25
|
+
ignoreParamsDTO: [], // string[];
|
|
26
|
+
deleteParentDTO: [], // (string | RegExp)[];
|
|
27
|
+
},
|
|
28
|
+
],
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
module.exports = config;
|
|
32
|
+
```
|
package/bin/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface ConfigModels {
|
|
2
|
+
outputPath?: string;
|
|
3
|
+
api: string;
|
|
4
|
+
projects: {
|
|
5
|
+
projectId: number | undefined;
|
|
6
|
+
branchId: number | undefined;
|
|
7
|
+
creatBaseFile?: boolean;
|
|
8
|
+
outputDirName?: string;
|
|
9
|
+
apiBaseName?: string;
|
|
10
|
+
ignoreParamsDTO?: string[];
|
|
11
|
+
deleteParentDTO?: (string | RegExp)[];
|
|
12
|
+
}[]
|
|
13
|
+
}
|
package/bin/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
var M=(b,$,f)=>new Promise((x,w)=>{var c=h=>{try{a(f.next(h))}catch(I){w(I)}},l=h=>{try{a(f.throw(h))}catch(I){w(I)}},a=h=>h.done?x(h.value):Promise.resolve(h.value).then(c,l);a((f=f.apply(b,$)).next())});(function(b,$){typeof exports=="object"&&typeof module!="undefined"?$(require("axios")):typeof define=="function"&&define.amd?define(["axios"],$):$((b=typeof globalThis!="undefined"?globalThis:b||self).axios)})(this,function(b){"use strict";function $(t){return t&&typeof t=="object"&&"default"in t?t:{default:t}}var f=$(b);const x=t=>{var i;const o=(t||"").toLowerCase(),e={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:r}=((i=/^list<(?<listType>.+)>$/.exec(o))==null?void 0:i.groups)||{};return r?`Array<${e[r]||"any"}>`:e[o]||"any"},w=Object.freeze({_getDesc(t){const o=(t.title||"").trim();return o?` // ${o}`:""},getInterface:function({list:t,config:{ignoreParamsDTO:o,deleteParentDTO:e}}){const r=t.filter(i=>!i.id);return t.filter(i=>i.id&&!o.includes(i.type)).map(i=>{if(i.id&&i.json){const s=i.json.split(`
|
|
2
|
+
`);return s.forEach((d,n)=>{var y;const u=/(?<space>\s*)"(?<name>[a-zA-Z0-9]+)"\s?:\s*"(?<desc>.*)".*$/;if(u.test(d)){const{space:p,name:g,desc:j}=((y=u.exec(d))==null?void 0:y.groups)||{},S=(g||"").trim(),B=(j||"").trim(),D=r.filter(F=>(F.name||"").trim()+(F.title||"").trim()===S+B);if(D.length>=1){const[{type:F}]=D,L=i.required?"?":"";s[n]=d.replace(u,`${p+g+L}: ${x(F)};${B?` // ${B}`:""}`)}}/\s*"[a-zA-Z0-9]+"\s*:\s*.+$/.test(d)&&(s[n]=s[n].replace(/(\s*)"([a-zA-Z0-9]+)"\s?(:\s*.+)$/,"$1$2$3")),s[n]=s[n].replace(/(.*)\[\s+{$/,"$1Array<{").replace(/(.*)}\s*].*$/,"$1}>")}),e.some(d=>{const n=Object.prototype.toString.call(d);return n==="[object RegExp]"?d.test(i.type):n==="[object String]"?d===i.type:void 0})?s.slice(1,-1).join(`
|
|
3
|
+
`):[` ${i.name}${i.required?"":"?"}: {${this._getDesc(i)}`,...s.slice(1,-1).map(d=>` ${d}`)," }"].join(`
|
|
4
|
+
`)}return` ${i.name}${i.required?"":"?"}: ${x(i.type)};${this._getDesc(i)}`})}}),c=require("fs"),l=require("path"),a=require("chalk");f.default.interceptors.response.use(t=>{var o,e;return((e=(o=t.data)==null?void 0:o.head)==null?void 0:e.successful)?t:Promise.reject(t)},t=>{throw t});const h=require("path"),{program:I}=require("commander"),P=require("chalk");I.version(require(h.resolve(__dirname,"../package.json")).version).requiredOption("-i, --id <id>","methodId").option("-n, --name <name>","customMethodName").requiredOption("--config <filePath>","configFilePath").requiredOption("--project-id <id>","projectId").parse();const{id:O,name:v,config:R,projectId:A}=I.opts();if(!O||!/^\d+$/.test(O))throw P.red("\u3010error\u3011\u8BF7\u4F20\u5165\u6B63\u786E\u7684 id");const q=require(h.resolve(process.cwd(),R)),m=(q.projects||[]).find(t=>+t.projectId==+A);if(m){if(!m.branchId)throw P.red("\u3010error\u3011\u8BF7\u4F20\u5165\u6B63\u786E\u7684 branchId");if(!q.api)throw P.red("\u3010error\u3011\u8BF7\u4F20\u5165\u6B63\u786E\u7684 api");new class{constructor(t){this.config={api:"",creatBaseFile:!0,customMethodName:"",projectId:void 0,branchId:void 0,methodId:void 0,outputPath:"",outputDirName:"",apiBaseName:"",ignoreParamsDTO:[],deleteParentDTO:[]},this.apiList=[],this.enums=[],Object.assign(this.config,t),this.getApiData()}getApiData(){return M(this,null,function*(){const{api:t,branchId:o,projectId:e,outputDirName:r,outputPath:i,methodId:s,creatBaseFile:d}=this.config;try{const{data:n}=yield f.default.get(`${t}/api/project/getProjectWithBranchById?id=${e}`);this.config.outputPath=l.join(process.cwd(),i,r||n.body.name);const u=n.body.branchList.find(p=>p.id===o);if(!u)throw a.red(`\u3010error\u3011branchId ${o} \u4E0D\u5B58\u5728`);console.log(a.blueBright(`\u3010info\u3011\u6B63\u5728\u4F7F\u7528 branchName: ${u.name} branchId: ${o} methodId: ${s}`));const y=yield f.default.get(`${t}/api/method/getMethodById?id=${s}`);this.apiList=[y.data.body]}catch(n){return console.log(a.red("\u3010error\u3011: \u63A5\u53E3\u83B7\u53D6\u5F02\u5E38")),void console.log(n)}try{yield this.checkApiOutputDir()}catch(n){return console.log(a.red("\u3010error\u3011: \u68C0\u67E5\u8F93\u51FA\u76EE\u5F55\u5F02\u5E38")),void console.log(n)}d&&(yield this.creatBaseFile());try{yield this.createFile()}catch(n){console.log(a.red("\u3010error\u3011: createFile \u5F02\u5E38")),console.log(n)}})}checkApiOutputDir(){const{outputPath:t}=this.config;console.log(a.blueBright(`\u3010info\u3011\u8F93\u51FA\u76EE\u5F55 ${t}`));try{c.statSync(t,{bigint:!0})}catch(o){c.mkdirSync(t,{recursive:!0})}}creatBaseFile(){return M(this,null,function*(){const{outputPath:t}=this.config,o=l.join(__dirname,"../template"),e=c.readdirSync(o),r=c.readdirSync(t);for(const i of e)if(!r.includes(i))try{const s=c.readFileSync(l.join(o,i));c.writeFileSync(l.join(t,i),s)}catch(s){console.log(a.red("\u3010error\u3011: \u57FA\u7840\u6587\u4EF6\u751F\u6210\u5F02\u5E38")),console.log(s)}})}createFile(){return M(this,null,function*(){const{apiBaseName:t,outputPath:o}=this.config;this.apiList.sort((e,r)=>e.path.localeCompare(r.path)),this.apiList.slice(0,1e3).forEach(e=>{var y;const r=e.path.replace(t,"").split("/")[1],i=p=>p.replace(/(-[a-z])|(^[a-z])/g,g=>g.replace("-","").toLocaleUpperCase()),s=i((e.name.startsWith(r)?"":`${r}-`)+e.name);try{c.statSync(l.join(o,r)).isDirectory()}catch(p){c.mkdirSync(l.join(o,r))}const d=(y=e.paramList)==null?void 0:y.length;let n=[];try{n=["/**************************************************/",...d?[`/** ${e.title} RequestModel */`,`export interface ${s}ReqModel {`,...w.getInterface({list:e.paramList||[],config:this.config}),"}",""]:[],`/** ${e.title} ResponseModel */`,`export interface ${s}ResModel {`,...w.getInterface({list:e.returnList||[],config:this.config}),"}",""]}catch(p){throw console.log(a.red(`\u3010error\u3011\u7C7B\u578B\u751F\u6210\u5931\u8D25 projectId: ${this.config.projectId} methodId: ${e.id} path: ${e.path}`)),a.red(p)}try{c.readFileSync(l.join(o,r,"models.ts")).toString().includes(`export interface ${s}ReqModel {`)?console.log(a.yellowBright(`\u3010warning\u3011models.ts \u5DF2\u5B58\u5728 ${s}ReqModel`)):(c.appendFileSync(l.join(o,`./${r}/models.ts`),[""].concat(n).join(`
|
|
5
|
+
`)),console.log(a.greenBright(`\u3010success\u3011models.ts \u6210\u529F\u6DFB\u52A0 ${s}ReqModel`)))}catch(p){c.writeFileSync(l.join(o,`./${r}/models.ts`),n.join(`
|
|
6
|
+
`)),console.log(a.greenBright(`\u3010success\u3011models.ts \u6210\u529F\u6DFB\u52A0 ${s}ReqModel`))}const u=[` /** ${e.title} */`,` ${e.name}(${d?`params: M.${s}ReqModel`:""}) {`,` return axios.${e.method.toLowerCase()}<ApiResponse<M.${s}ResModel>>(`,` \`\${ApiPrefix}/${e.path}\`,`,d&&` ${["post","put","patch"].includes(e.method.toLowerCase())?"params":"{ params }"},`," );"," },"].filter(Boolean);/^[a-zA-Z]+$/.test((e.method||"").trim())||console.log(a.yellowBright(`\u3010warning\u3011\u63A5\u53E3\u8BF7\u6C42\u7C7B\u578B\u5F02\u5E38\uFF0C\u8BF7\u624B\u52A8\u8865\u5168 method\uFF1A${e.method} path: ${e.path} methodId: ${this.config.methodId} projectId: ${this.config.projectId}`));try{const p=c.readFileSync(l.join(o,r,"api.ts")).toString();if(p.includes(` ${e.name}(`))console.log(a.yellowBright(`\u3010warning\u3011api.ts \u5DF2\u5B58\u5728 ${e.name}`));else{const g=p.split(`
|
|
7
|
+
`);g.splice(g.map(j=>j.includes("}")).lastIndexOf(!0),0,u.join(`
|
|
8
|
+
`)),c.writeFileSync(l.join(o,`./${r}/api.ts`),g.join(`
|
|
9
|
+
`)),console.log(a.blueBright(`\u3010success\u3011api.ts \u6210\u529F\u6DFB\u52A0 ${e.name}`))}}catch(g){c.writeFileSync(l.join(o,`./${r}/api.ts`),["import axios from 'axios';","","import * as M from './models';","import { ApiResponse } from '../responseModel'","import { ApiPrefix } from '../apiPrefix'","","export * from './models';","",`export const ${i(r)}Api = {`,...u,"};"].join(`
|
|
10
|
+
`)),console.log(a.blueBright(`\u3010success\u3011api.ts \u6210\u529F\u6DFB\u52A0 ${e.name}`));const p=c.readFileSync(l.join(o,"index.ts")).toString();if(!p.includes(`export * from './${r}/api'`)){const j=p.split(`
|
|
11
|
+
`);j.push(`export * from './${r}/api';`);const S=j.slice(1).filter(Boolean);S.sort((B,D)=>B.localeCompare(D)),c.writeFileSync(l.join(o,"index.ts"),[j[0]||"","",...S,""].join(`
|
|
12
|
+
`))}}})})}}({api:q.api,creatBaseFile:m.creatBaseFile||!0,methodId:O,customMethodName:v,outputPath:q.outputPath||"./src/apis",projectId:m.projectId,branchId:+m.branchId,outputDirName:m.outputDirName||"",apiBaseName:m.apiBaseName||"",ignoreParamsDTO:m.ignoreParamsDTO||[],deleteParentDTO:m.deleteParentDTO||[]})}else console.log(P.red(`\u3010error\u3011config \u914D\u7F6E\u6587\u4EF6\u4E2D projects \u672A\u5305\u542B\u4F20\u5165\u7684 projectId ${A}`))});
|
package/package.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "sy-api-pro",
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"main": "./bin/index.js",
|
|
5
|
+
"types": "./bin/index.d.ts",
|
|
6
|
+
"bin": {
|
|
7
|
+
"sy-api-pro": "./bin/index.js"
|
|
8
|
+
},
|
|
9
|
+
"license": "MIT",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"import": "./dist/index.umd.js",
|
|
13
|
+
"require": "./dist/index.umd.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"/bin",
|
|
18
|
+
"/dist",
|
|
19
|
+
"/template"
|
|
20
|
+
],
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "vite build",
|
|
23
|
+
"api": "ts-node src/index.ts --config ./src/.api-config.ts --project-id 804"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"axios": "^0.24.0",
|
|
27
|
+
"chalk": "^4.1.2",
|
|
28
|
+
"commander": "^8.3.0",
|
|
29
|
+
"ts-node": "^10.4.0"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/node": "^17.0.5",
|
|
33
|
+
"rollup-plugin-terser": "^7.0.2",
|
|
34
|
+
"typescript": "^4.5.4",
|
|
35
|
+
"vite": "^2.7.10"
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const ApiPrefix = '';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import './interceptors';
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import axios, { AxiosResponse } from 'axios';
|
|
2
|
+
|
|
3
|
+
import { ApiPrefix } from './apiPrefix';
|
|
4
|
+
|
|
5
|
+
axios.interceptors.request.use(config => config, error => Promise.reject(error));
|
|
6
|
+
axios.interceptors.response.use((response: AxiosResponse) => {
|
|
7
|
+
if (!response.config.url?.startsWith(ApiPrefix)) return;
|
|
8
|
+
//
|
|
9
|
+
// if (response.data?.success) {
|
|
10
|
+
// return response;
|
|
11
|
+
// }
|
|
12
|
+
console.log(response.data);
|
|
13
|
+
return Promise.reject(response);
|
|
14
|
+
}, (error) => {
|
|
15
|
+
console.error(error);
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
|