@dypnb/dev-tools 1.0.0 → 1.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,203 +1 @@
1
- import require$$0$1 from 'path';
2
- import require$$0 from 'fs';
3
- import http from 'http';
4
- import { j as getDirname, e as getGlobalConfig, i as errorLog, l as log, s as successLog } from '../chunk-cb5f11a8.js';
5
- import 'os';
6
- import 'util';
7
- import 'tty';
8
- import 'child_process';
9
- import 'assert';
10
- import 'events';
11
- import 'buffer';
12
- import 'stream';
13
- import 'node:url';
14
- import 'node:path';
15
-
16
- // 将swagger 转换为 vue api代码
17
- const __dirname = getDirname();
18
- // swagger配置
19
- const swaggerConfig = await getGlobalConfig('swaggerConfig');
20
- if (!swaggerConfig) {
21
- errorLog('swaggerConfig 未配置');
22
- }
23
-
24
- // 生成api文件地址
25
- const srcFolder = `${process.env.PWD}${swaggerConfig.outputDir}`;
26
- // swagger接口地址
27
- const url = `${swaggerConfig.path}${swaggerConfig.staticPath}`;
28
-
29
- // 生成本地文件
30
- function mkdirsSync(dirname) {
31
- if (require$$0.existsSync(dirname)) {
32
- return true;
33
- } else {
34
- if (mkdirsSync(require$$0$1.dirname(dirname))) {
35
- require$$0.mkdirSync(dirname);
36
- return true;
37
- }
38
- }
39
- }
40
- function getPath(pathUrl) {
41
- return require$$0$1.resolve(__dirname, pathUrl);
42
- }
43
- function generateTemplate(arr) {
44
- return `import request from '@/utils/request'\n`;
45
- }
46
-
47
- // 下划线转换驼峰
48
- function toHump(name) {
49
- return name.replace(/\/(\w)/g, function (all, letter) {
50
- return letter.toUpperCase();
51
- });
52
- }
53
-
54
- // 短横线转换驼峰
55
- function shortToHump(name) {
56
- return name.replace(/-(\w)/g, function (all, letter) {
57
- return letter.toUpperCase();
58
- });
59
- }
60
-
61
- // 去除花括号,获取干净的字段
62
- function removeBrace(value) {
63
- const regex = /\{(.+?)\}/g; // {} 花括号,大括号
64
- const str = value.match(regex)[0] || "";
65
- return str.replace(/\{|}/g, "");
66
- }
67
-
68
- /**
69
- * 生成具体的api:
70
- * export function postRsArticle(data) {
71
- * return request({
72
- * url: '/rs/article',
73
- * method: 'post',
74
- * data: data
75
- * })
76
- * }
77
- */
78
- function generateFunc(url, summary, type = "post") {
79
- // 去除 url 环境前缀: /dev-risk-api/sc/apply/{applyId} ==> /sc/apply/{applyId}
80
- // url = url.split('/');
81
- // url.splice(1,1)
82
- // url = url.join('/');
83
-
84
- const isBrace = url.indexOf("{") !== -1;
85
- let funcName = shortToHump(toHump(type + url));
86
- let splitUrl = "";
87
- let braceKey = "";
88
- if (isBrace) {
89
- splitUrl = url.split("{")[0];
90
- braceKey = removeBrace(url);
91
- funcName = shortToHump(toHump(type + splitUrl + braceKey));
92
- }
93
- const funcArguments = `${isBrace ? braceKey : !isBrace && (type === "post" || type === "put") ? "data" : "query"}`;
94
- const funcUrl = `${!isBrace ? `'${url}'` : `'${splitUrl}' + ${braceKey}`}`;
95
- const funcParams = `${isBrace ? "" : !isBrace && (type === "post" || type === "put") ? "\n data: data" : "\n params: query"}`;
96
- return `
97
- // ${summary || ""}
98
- export function ${funcName}(${funcArguments}) {
99
- return request({
100
- url: ${funcUrl},
101
- method: '${type}', ${funcParams}
102
- })
103
- }\n`;
104
- }
105
- function httpgetJson(url) {
106
- return new Promise((resolve, reject) => {
107
- http.get(url, res => {
108
- const {
109
- statusCode
110
- } = res;
111
- const contentType = res.headers["content-type"];
112
- let error;
113
- if (statusCode !== 200) {
114
- error = new Error("请求失败。\n" + `状态码: ${statusCode}`);
115
- } else if (!/^application\/json/.test(contentType)) {
116
- error = new Error("无效的 content-type.\n" + `期望 application/json 但获取的是 ${contentType}`);
117
- }
118
- if (error) {
119
- errorLog(error.message);
120
- // 消耗响应数据以释放内存
121
- res.resume();
122
- return;
123
- }
124
- res.setEncoding("utf8");
125
- let rawData = "";
126
- res.on("data", chunk => {
127
- rawData += chunk;
128
- });
129
- res.on("end", () => {
130
- try {
131
- const parsedData = JSON.parse(rawData);
132
- resolve(parsedData);
133
- } catch (e) {
134
- reject(`错误: ${e.message}`);
135
- }
136
- });
137
- }).on("error", e => {
138
- reject(`错误: ${e.message}`);
139
- });
140
- });
141
- }
142
- async function genSwagger() {
143
- log("获取远程json文件中...");
144
- const {
145
- paths
146
- } = await httpgetJson(url);
147
- successLog("获取成功正在生成api文件");
148
- const obj = {};
149
- /**
150
- * 将数据转换成格式
151
- * se-ex-exam-controller: [
152
- * {
153
- * folder:'exam'
154
- * name:'/ex/exam'
155
- * summary:'修改考试考卷'
156
- * tag:'se-ex-exam-controller'
157
- * type:'put'
158
- * }
159
- * ...
160
- * ]
161
- */
162
- for (const name in paths) {
163
- const path = paths[name] || {};
164
- const pathKeys = Object.keys(path) || [];
165
- for (let i = 0, len = pathKeys.length; i < len; i++) {
166
- const apiType = pathKeys[i];
167
- const tag = path[apiType].tags[0];
168
- if (!tag) continue;
169
- log(tag);
170
- const urlArray = name.slice(1).split("/");
171
- const folder = urlArray[1];
172
- const item = {
173
- summary: path[apiType].summary,
174
- tag,
175
- name,
176
- type: apiType,
177
- folder
178
- };
179
- if (obj[path[apiType].tags[0]]) {
180
- obj[path[apiType].tags[0]].push(item);
181
- } else {
182
- obj[path[apiType].tags[0]] = [item];
183
- }
184
- }
185
- }
186
- for (const tagName in obj) {
187
- let jsString = "";
188
- const requestTypes = [];
189
- let folder = "";
190
- for (const item of obj[tagName]) {
191
- const requestType = requestTypes.filter(o => o === item.type);
192
- if (requestType.length === 0) requestTypes.push(item.type);
193
- jsString += generateFunc(item.name, item.summary, item.type);
194
- folder = item.folder;
195
- }
196
- jsString = generateTemplate() + jsString;
197
- mkdirsSync(getPath(`${srcFolder}/${folder}`));
198
- // console.log(jsString)
199
- require$$0.writeFileSync(getPath(`${srcFolder}/${folder}/${tagName}.js`), jsString);
200
- }
201
- successLog("生成完毕");
202
- }
203
- genSwagger();
1
+ import t from"path";import e from"fs";import n from"http";import{j as r,e as o,i as s,l as a,s as i}from"../chunk-f4ef292d.js";import"os";import"util";import"tty";import"child_process";import"assert";import"events";import"buffer";import"stream";import"node:url";import"node:path";const p=r(),c=await o("swaggerConfig");c||s("swaggerConfig 未配置");const u=`${process.env.PWD}${c.outputDir}`,m=`${c.path}${c.staticPath}`;function f(n){return!!e.existsSync(n)||(f(t.dirname(n))?(e.mkdirSync(n),!0):void 0)}function l(e){return t.resolve(p,e)}function $(t){return t.replace(/\/(\w)/g,(function(t,e){return e.toUpperCase()}))}function g(t){return t.replace(/-(\w)/g,(function(t,e){return e.toUpperCase()}))}function d(t,e,n="post"){const r=-1!==t.indexOf("{");let o=g($(n+t)),s="",a="";r&&(s=t.split("{")[0],a=(t.match(/\{(.+?)\}/g)[0]||"").replace(/\{|}/g,""),o=g($(n+s+a)));return`\n// ${e||""}\nexport function ${o}(${`${r?a:r||"post"!==n&&"put"!==n?"query":"data"}`}) {\n return request({\n url: ${""+(r?`'${s}' + ${a}`:`'${t}'`)},\n method: '${n}', ${""+(r?"":r||"post"!==n&&"put"!==n?"\n params: query":"\n data: data")}\n })\n}\n`}!async function(){a("获取远程json文件中...");const{paths:t}=await function(t){return new Promise(((e,r)=>{n.get(t,(t=>{const{statusCode:n}=t,o=t.headers["content-type"];let a;if(200!==n?a=new Error(`请求失败。\n状态码: ${n}`):/^application\/json/.test(o)||(a=new Error(`无效的 content-type.\n期望 application/json 但获取的是 ${o}`)),a)return s(a.message),void t.resume();t.setEncoding("utf8");let i="";t.on("data",(t=>{i+=t})),t.on("end",(()=>{try{const t=JSON.parse(i);e(t)}catch(t){r(`错误: ${t.message}`)}}))})).on("error",(t=>{r(`错误: ${t.message}`)}))}))}(m);i("获取成功正在生成api文件");const r={};for(const e in t){const n=t[e]||{},o=Object.keys(n)||[];for(let t=0,s=o.length;t<s;t++){const s=o[t],i=n[s].tags[0];if(!i)continue;a(i);const p=e.slice(1).split("/")[1],c={summary:n[s].summary,tag:i,name:e,type:s,folder:p};r[n[s].tags[0]]?r[n[s].tags[0]].push(c):r[n[s].tags[0]]=[c]}}for(const t in r){let n="";const o=[];let s="";for(const e of r[t]){0===o.filter((t=>t===e.type)).length&&o.push(e.type),n+=d(e.name,e.summary,e.type),s=e.folder}n="import request from '@/utils/request'\n"+n,f(l(`${u}/${s}`)),e.writeFileSync(l(`${u}/${s}/${t}.js`),n)}i("生成完毕")}();