mock-service-cli 3.7.0 → 4.1.0
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/bin/mock-service-cli +1 -266
- package/dist/asyncTaskQueue.js +1 -0
- package/dist/cli.js +1 -0
- package/dist/fileExplorerServer.js +1 -0
- package/dist/manageMockFiles.js +1 -0
- package/dist/mockServer.js +1 -0
- package/dist/packageInfo.js +1 -0
- package/dist/runtime.js +144 -0
- package/dist/staticServer.js +1 -0
- package/dist/utils.js +1 -0
- package/package.json +21 -17
- package/lib/asyncTaskQueue.js +0 -74
- package/lib/fileExplorerServer.js +0 -330
- package/lib/manageMockFiles.js +0 -252
- package/lib/mockServer.js +0 -497
- package/lib/staticServer.js +0 -104
- package/lib/utils.js +0 -297
- /package/{lib → dist}/api-overview.html +0 -0
- /package/{lib → dist}/file-explorer.html +0 -0
package/lib/manageMockFiles.js
DELETED
|
@@ -1,252 +0,0 @@
|
|
|
1
|
-
/*
|
|
2
|
-
* @description: 生成Mock文件、获取mock数据统计
|
|
3
|
-
* @Date: 2021-12-22 16:57:08
|
|
4
|
-
* @LastEditors: chendq
|
|
5
|
-
* @LastEditTime: 2025-06-15 22:25:45
|
|
6
|
-
* @Author: chendq
|
|
7
|
-
*/
|
|
8
|
-
const fsa = require('fs-extra'),
|
|
9
|
-
fs = require('fs'),
|
|
10
|
-
path = require('path'),
|
|
11
|
-
isEqual = require('lodash/isEqual'),
|
|
12
|
-
colors = require('colors/safe');
|
|
13
|
-
const {
|
|
14
|
-
getFileLatestContent,
|
|
15
|
-
SupportMethods,
|
|
16
|
-
filePath2ApiUrl,
|
|
17
|
-
logger,
|
|
18
|
-
getDataType,
|
|
19
|
-
getLogger,
|
|
20
|
-
writeStream
|
|
21
|
-
} = require('./utils');
|
|
22
|
-
const log = logger(process.env.SILENT);
|
|
23
|
-
const processArgv = process.env.ARGV ? JSON.parse(process.env.ARGV) : {};
|
|
24
|
-
|
|
25
|
-
const methodRegExp = new RegExp(`(${SupportMethods.join('|')}) +(.*)`, 'i');
|
|
26
|
-
/**
|
|
27
|
-
* @description: 记录日志文件函数
|
|
28
|
-
* @param {boolean} isWriteLogFile 是否写入日志文件
|
|
29
|
-
* @param {string} mockDir 存放日志文件的目录
|
|
30
|
-
* @return {object}
|
|
31
|
-
*/
|
|
32
|
-
const logFile = (isWriteLogFile = false, mockDir) => {
|
|
33
|
-
if (isWriteLogFile) {
|
|
34
|
-
return getLogger(mockDir);
|
|
35
|
-
}
|
|
36
|
-
return {
|
|
37
|
-
log: function () {},
|
|
38
|
-
error: function () {}
|
|
39
|
-
};
|
|
40
|
-
};
|
|
41
|
-
/**
|
|
42
|
-
* @description: 生成mock文件(自动生成mock-list.json文件,并维护<url, [method]>的关系映射)
|
|
43
|
-
* @param {string} apiUrl 请求url
|
|
44
|
-
* @param {string} method 请求方法
|
|
45
|
-
* @param {object} resJsonData 响应数据
|
|
46
|
-
* @param {string} mockDir mock目录
|
|
47
|
-
* @return {*} void
|
|
48
|
-
*
|
|
49
|
-
*/
|
|
50
|
-
const genMockFiles = async function ({ url: apiUrl, method, data: resJsonData, dir: mockDir }) {
|
|
51
|
-
const type = getDataType(resJsonData);
|
|
52
|
-
if (!apiUrl || !method || !resJsonData || !mockDir) {
|
|
53
|
-
log.info(
|
|
54
|
-
colors.red([`参数: apiUrl: ${apiUrl}, method: ${method}, mockDir: ${mockDir} `, `必须是有效值`].join(','))
|
|
55
|
-
);
|
|
56
|
-
return;
|
|
57
|
-
} else if (
|
|
58
|
-
!['object', 'array'].includes(type) ||
|
|
59
|
-
(type === 'object' && Object.keys(resJsonData).length === 0) ||
|
|
60
|
-
(type === 'array' && resJsonData.length === 0)
|
|
61
|
-
) {
|
|
62
|
-
log.info(
|
|
63
|
-
`参数: apiUrl: ${apiUrl}, method: ${method}, resJsonData:`,
|
|
64
|
-
resJsonData,
|
|
65
|
-
colors.red(', 参数字段resJsonData必须是非空的数组或对象!')
|
|
66
|
-
);
|
|
67
|
-
return;
|
|
68
|
-
}
|
|
69
|
-
apiUrl = apiUrl.trim().split('?')[0];
|
|
70
|
-
const LOGGER = logFile(processArgv.t || processArgv.track, mockDir);
|
|
71
|
-
const normalizeApiUrl = filePath2ApiUrl(path.normalize(apiUrl));
|
|
72
|
-
const mockListFilePath = path.resolve(process.cwd(), `${mockDir}/mock-list.json`);
|
|
73
|
-
const mockFilePath = path.resolve(process.cwd(), `${mockDir}/${encodeURIComponent(path.normalize(apiUrl))}.json`);
|
|
74
|
-
let newMockListContent = {};
|
|
75
|
-
if (fsa.pathExistsSync(mockListFilePath)) {
|
|
76
|
-
newMockListContent = getFileLatestContent(mockListFilePath);
|
|
77
|
-
} else {
|
|
78
|
-
fsa.ensureFileSync(mockListFilePath);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
let isChange = false;
|
|
82
|
-
// update mock-list.json file
|
|
83
|
-
if (!newMockListContent.hasOwnProperty(normalizeApiUrl)) {
|
|
84
|
-
newMockListContent[normalizeApiUrl] = [method];
|
|
85
|
-
isChange = true;
|
|
86
|
-
} else if (!newMockListContent[normalizeApiUrl].includes(method)) {
|
|
87
|
-
newMockListContent[normalizeApiUrl].push(method);
|
|
88
|
-
isChange = true;
|
|
89
|
-
}
|
|
90
|
-
if (isChange) {
|
|
91
|
-
Object.keys(newMockListContent).length > 0 &&
|
|
92
|
-
fs.writeFileSync(mockListFilePath, JSON.stringify(newMockListContent, null, 2));
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
// mock文件存在
|
|
96
|
-
if (fsa.pathExistsSync(mockFilePath)) {
|
|
97
|
-
const mockFileContent = getFileLatestContent(mockFilePath);
|
|
98
|
-
// 内容一样不作修改
|
|
99
|
-
if (mockFileContent.hasOwnProperty(method) && isEqual(mockFileContent[method], resJsonData)) {
|
|
100
|
-
// log.assert(
|
|
101
|
-
// !_.isEqual(mockFileContent[method], resJsonData),
|
|
102
|
-
// colors.bgYellow(`${method} ${apiUrl}, Mock data is same`)
|
|
103
|
-
// );
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
mockFileContent[method] = resJsonData;
|
|
107
|
-
try {
|
|
108
|
-
await writeStream(mockFilePath, JSON.stringify(mockFileContent, null, 2));
|
|
109
|
-
} catch (error) {
|
|
110
|
-
LOGGER.error(`Update file: ${method} ${apiUrl} ${mockFilePath}`);
|
|
111
|
-
}
|
|
112
|
-
LOGGER.log(`Update file: ${method} ${apiUrl} ${mockFilePath}`);
|
|
113
|
-
} else {
|
|
114
|
-
try {
|
|
115
|
-
await writeStream(mockFilePath, JSON.stringify({ [method]: resJsonData }, null, 2));
|
|
116
|
-
} catch (error) {
|
|
117
|
-
LOGGER.error(`New file: ${method} ${apiUrl} ${mockFilePath}`);
|
|
118
|
-
}
|
|
119
|
-
LOGGER.log(`New file: ${method} ${apiUrl} ${mockFilePath}`);
|
|
120
|
-
}
|
|
121
|
-
// console.debug('file::', `${mockDir}/${apiUrl}`, newMockListContent);
|
|
122
|
-
};
|
|
123
|
-
/**
|
|
124
|
-
* @description: 从js文件中收集mock数据
|
|
125
|
-
* @param {object} mockDataMap
|
|
126
|
-
* @param {string} filePath
|
|
127
|
-
* @return {*} void
|
|
128
|
-
*/
|
|
129
|
-
const collectMockDataFromJsFile = function (mockDataMap, filePath) {
|
|
130
|
-
// 先删除require之前导入的缓存文件,否则获取到的文件内容还是旧内容
|
|
131
|
-
const fileObject = getFileLatestContent(filePath);
|
|
132
|
-
|
|
133
|
-
Object.keys(fileObject).forEach(item => {
|
|
134
|
-
let reqMethod = 'get',
|
|
135
|
-
reqUrl = item;
|
|
136
|
-
if (methodRegExp.exec(item)) {
|
|
137
|
-
const [, method, url] = methodRegExp.exec(item);
|
|
138
|
-
reqMethod = method.toLowerCase();
|
|
139
|
-
reqUrl = path.normalize(url);
|
|
140
|
-
}
|
|
141
|
-
if (typeof fileObject[item] === 'function') {
|
|
142
|
-
mockDataMap[`${reqMethod} ${reqUrl}`] = String(fileObject[item]);
|
|
143
|
-
} else if (typeof fileObject[item] === 'object') {
|
|
144
|
-
mockDataMap[`${reqMethod} ${reqUrl}`] = fileObject[item];
|
|
145
|
-
}
|
|
146
|
-
});
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
/**
|
|
150
|
-
* @description: 递归收集mock数据
|
|
151
|
-
* @param {object} mockDataMap mock数据集
|
|
152
|
-
* @param {string} specialDir 目录
|
|
153
|
-
* @return {*} void
|
|
154
|
-
*/
|
|
155
|
-
const deepCollectMockData = function (mockDataMap, specialDir = '../mock') {
|
|
156
|
-
const files = fs.readdirSync(path.resolve(process.cwd(), specialDir), { withFileTypes: true });
|
|
157
|
-
const curFilesSize = files.length;
|
|
158
|
-
for (let index = 0; index < curFilesSize; index++) {
|
|
159
|
-
const el = files[index];
|
|
160
|
-
const filePath = path.normalize(`${specialDir}/${el.name}`);
|
|
161
|
-
// 递归目录
|
|
162
|
-
if (!el.isFile()) {
|
|
163
|
-
deepCollectMockData(mockDataMap, filePath);
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
// 处理存放mock数据的json文件
|
|
167
|
-
if (el.name.endsWith('.json') && el.name !== 'mock-list.json') {
|
|
168
|
-
const fileObject = getFileLatestContent(filePath);
|
|
169
|
-
Object.keys(fileObject).forEach(method => {
|
|
170
|
-
mockDataMap[`${method.toLocaleLowerCase()} ${decodeURIComponent(el.name).split('.json')[0]}`] =
|
|
171
|
-
fileObject[method];
|
|
172
|
-
});
|
|
173
|
-
continue;
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
// 非js文件跳过
|
|
177
|
-
if (!el.name.endsWith('.js')) {
|
|
178
|
-
continue;
|
|
179
|
-
}
|
|
180
|
-
collectMockDataFromJsFile(mockDataMap, filePath);
|
|
181
|
-
}
|
|
182
|
-
};
|
|
183
|
-
/**
|
|
184
|
-
* @description: 从文件目录中获取mock数据统计(若mock-list.json文件不存在则自动生成)
|
|
185
|
-
* @param {string} dirPath
|
|
186
|
-
* @return {object} mock数据统计
|
|
187
|
-
*/
|
|
188
|
-
const getMockStatFromDir = dirPath => {
|
|
189
|
-
if (!fsa.pathExistsSync(dirPath)) {
|
|
190
|
-
getLogger(path.resolve(process.cwd())).error(`入参无效,${dirPath} 目录不存在`);
|
|
191
|
-
return;
|
|
192
|
-
}
|
|
193
|
-
const mockDataMap = {};
|
|
194
|
-
deepCollectMockData(mockDataMap, dirPath);
|
|
195
|
-
|
|
196
|
-
const mockListFilePath = path.resolve(process.cwd(), `${dirPath}/mock-list.json`);
|
|
197
|
-
// 若不存在mock-list.json文件,则根据现有mock文件重新生成<api, [method]>映射关系
|
|
198
|
-
if (Object.keys(mockDataMap).length > 0 && !fsa.pathExistsSync(mockListFilePath)) {
|
|
199
|
-
fsa.ensureFileSync(mockListFilePath);
|
|
200
|
-
const reverseMockList = {};
|
|
201
|
-
Object.keys(mockDataMap).forEach(it => {
|
|
202
|
-
if (methodRegExp.exec(it)) {
|
|
203
|
-
const [, method, url] = methodRegExp.exec(it);
|
|
204
|
-
if (url.trim() && method.trim()) {
|
|
205
|
-
if (reverseMockList.hasOwnProperty(url)) {
|
|
206
|
-
reverseMockList[url].push(method);
|
|
207
|
-
} else {
|
|
208
|
-
reverseMockList[url] = [method];
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
});
|
|
213
|
-
writeStream(mockListFilePath, JSON.stringify(reverseMockList, null, 2));
|
|
214
|
-
}
|
|
215
|
-
return mockDataMap;
|
|
216
|
-
};
|
|
217
|
-
|
|
218
|
-
/**
|
|
219
|
-
* @description: 从js文件中获取mock数据统计
|
|
220
|
-
* @param {string} filePath
|
|
221
|
-
* @return {object} mock数据统计
|
|
222
|
-
*/
|
|
223
|
-
const getMockStatFromFile = filePath => {
|
|
224
|
-
if (!fsa.pathExistsSync(filePath)) {
|
|
225
|
-
getLogger(path.resolve(process.cwd())).error(`入参无效,${filePath} 文件不存在`);
|
|
226
|
-
return;
|
|
227
|
-
}
|
|
228
|
-
const mockDataMap = {};
|
|
229
|
-
collectMockDataFromJsFile(mockDataMap, filePath);
|
|
230
|
-
return mockDataMap;
|
|
231
|
-
};
|
|
232
|
-
/**
|
|
233
|
-
* @description: 判断Mock服务中是否存在某个API
|
|
234
|
-
* @param {object} mockDataMap
|
|
235
|
-
* @param {string} apiUrl
|
|
236
|
-
* @param {string} method
|
|
237
|
-
* @return {boolean}
|
|
238
|
-
*/
|
|
239
|
-
const hasMockApi = function (mockDataMap, apiUrl, method) {
|
|
240
|
-
if (!apiUrl || !method || !mockDataMap || !(mockDataMap instanceof Object)) {
|
|
241
|
-
getLogger(path.resolve(process.cwd())).error(`入参无效,${mockDataMap} 必须是 mock数据的Object对象`);
|
|
242
|
-
return;
|
|
243
|
-
}
|
|
244
|
-
return mockDataMap.hasOwnProperty(`${method.toLocaleLowerCase()} ${path.normalize(apiUrl)}`);
|
|
245
|
-
};
|
|
246
|
-
|
|
247
|
-
module.exports = {
|
|
248
|
-
genMockFiles,
|
|
249
|
-
getMockStatFromDir,
|
|
250
|
-
getMockStatFromFile,
|
|
251
|
-
hasMockApi
|
|
252
|
-
};
|