whistle.mock-plugins 1.0.6 → 1.1.1-beta.1

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.
@@ -3,6 +3,113 @@ const path = require('path');
3
3
  const url = require('url');
4
4
  const Mock = require('mockjs');
5
5
 
6
+ // 获取嵌套对象属性值的工具函数
7
+ const getNestedValue = (obj, path) => {
8
+ return path.split('.').reduce((current, key) => {
9
+ return current && current[key] !== undefined ? current[key] : undefined;
10
+ }, obj);
11
+ };
12
+
13
+ // 参数匹配功能
14
+ const isParamMatch = (req, paramMatchers, log) => {
15
+ if (!paramMatchers || !Array.isArray(paramMatchers) || paramMatchers.length === 0) {
16
+ return true; // 如果没有参数匹配规则,视为匹配成功
17
+ }
18
+
19
+ try {
20
+ // 合并所有可能的参数来源
21
+ let requestParams = {};
22
+
23
+ // URL查询参数
24
+ if (req.query) {
25
+ requestParams = { ...requestParams, ...req.query };
26
+ }
27
+
28
+ // POST请求体参数
29
+ if (req.body && typeof req.body === 'object') {
30
+ requestParams = { ...requestParams, ...req.body };
31
+ }
32
+
33
+ // URL路径参数(如果有的话)
34
+ if (req.params) {
35
+ requestParams = { ...requestParams, ...req.params };
36
+ }
37
+
38
+ if (log) {
39
+ log(`参数匹配检查 - 请求参数: ${JSON.stringify(requestParams)}`);
40
+ log(`参数匹配检查 - 匹配规则: ${JSON.stringify(paramMatchers)}`);
41
+ }
42
+
43
+ // 检查每个匹配规则
44
+ for (const matcher of paramMatchers) {
45
+ const { paramPath, paramValue, matchType = 'exact' } = matcher;
46
+
47
+ if (!paramPath) {
48
+ continue; // 跳过无效的匹配规则
49
+ }
50
+
51
+ // 获取实际参数值
52
+ const actualValue = getNestedValue(requestParams, paramPath);
53
+
54
+ if (log) {
55
+ log(`参数匹配检查 - 路径: ${paramPath}, 期望值: ${paramValue}, 实际值: ${actualValue}, 匹配类型: ${matchType}`);
56
+ }
57
+
58
+ // 如果参数不存在,视为不匹配
59
+ if (actualValue === undefined || actualValue === null) {
60
+ if (log) {
61
+ log(`参数匹配失败 - 参数 ${paramPath} 不存在`);
62
+ }
63
+ return false;
64
+ }
65
+
66
+ // 根据匹配类型进行比较
67
+ let isMatch = false;
68
+ const actualStr = String(actualValue);
69
+ const expectedStr = String(paramValue);
70
+
71
+ switch (matchType) {
72
+ case 'exact':
73
+ isMatch = actualStr === expectedStr;
74
+ break;
75
+ case 'contains':
76
+ isMatch = actualStr.includes(expectedStr);
77
+ break;
78
+ case 'regex':
79
+ try {
80
+ const regex = new RegExp(expectedStr);
81
+ isMatch = regex.test(actualStr);
82
+ } catch (e) {
83
+ if (log) {
84
+ log(`参数匹配失败 - 正则表达式无效: ${expectedStr}`);
85
+ }
86
+ return false;
87
+ }
88
+ break;
89
+ default:
90
+ isMatch = actualStr === expectedStr;
91
+ }
92
+
93
+ if (!isMatch) {
94
+ if (log) {
95
+ log(`参数匹配失败 - ${paramPath}: ${actualStr} 不匹配 ${expectedStr} (${matchType})`);
96
+ }
97
+ return false;
98
+ }
99
+ }
100
+
101
+ if (log) {
102
+ log('参数匹配成功 - 所有规则都匹配');
103
+ }
104
+ return true;
105
+ } catch (error) {
106
+ if (log) {
107
+ log(`参数匹配检查出错: ${error.message}`);
108
+ }
109
+ return false;
110
+ }
111
+ };
112
+
6
113
  /**
7
114
  * 规则管理模块,负责处理 Whistle 规则和代理请求
8
115
  */
@@ -60,7 +167,7 @@ const ruleManager = {
60
167
  const requestPath = parsedUrl.pathname;
61
168
 
62
169
  // 查找匹配的接口
63
- const matchedInterface = this.findMatchingInterface(enabledInterfaces, requestPath, req.method);
170
+ const matchedInterface = this.findMatchingInterface(enabledInterfaces, requestPath, req.method, req);
64
171
 
65
172
  if (!matchedInterface) {
66
173
  this.log(`[规则处理器] 未找到匹配的接口,请求将透传: ${req.method} ${requestPath}`);
@@ -93,9 +200,10 @@ const ruleManager = {
93
200
  * @param {Array} interfaces 接口列表
94
201
  * @param {string} requestPath 请求路径
95
202
  * @param {string} method 请求方法
203
+ * @param {object} req 完整的请求对象,用于参数匹配
96
204
  * @returns {object|null} 匹配的接口对象,如果没有匹配则返回 null
97
205
  */
98
- findMatchingInterface(interfaces, requestPath, method) {
206
+ findMatchingInterface(interfaces, requestPath, method, req) {
99
207
  // 简化日志,只记录正在进行匹配的操作
100
208
  this.log(`[规则处理器] 尝试匹配接口,路径: ${requestPath}, 方法: ${method}`);
101
209
 
@@ -111,17 +219,16 @@ const ruleManager = {
111
219
  return null;
112
220
  }
113
221
 
114
- // 先尝试完全匹配,效率更高
115
- let matchedInterface = interfaces.find(intf => {
116
- // 检查接口对象是否有效
222
+ // 收集所有URL匹配的接口
223
+ const urlMatchedInterfaces = [];
224
+
225
+ // 先收集所有URL匹配的接口(包括精确匹配和正则匹配)
226
+ for (const intf of interfaces) {
117
227
  if (!intf || !intf.urlPattern) {
118
- return false;
228
+ continue;
119
229
  }
120
230
 
121
- // 检查URL和方法是否匹配
122
- const urlMatches = intf.urlPattern === requestPath;
123
-
124
- // 修复: 兼容不同的方法名称和值
231
+ // 检查HTTP方法是否匹配
125
232
  const methodField = intf.httpMethod || intf.method;
126
233
  const methodValue = methodField && methodField.toUpperCase();
127
234
  const methodMatches = !methodValue ||
@@ -129,32 +236,24 @@ const ruleManager = {
129
236
  methodValue === 'ANY' ||
130
237
  methodValue === method;
131
238
 
132
- // 移除中间匹配过程的日志
133
- return urlMatches && methodMatches;
134
- });
135
-
136
- if (matchedInterface) {
137
- this.log(`[规则处理器] 找到完全匹配的接口: ${matchedInterface.name}`);
138
- return matchedInterface;
139
- }
140
-
141
- // 如果没有完全匹配,尝试正则表达式匹配
142
- this.log(`[规则处理器] 未找到完全匹配,尝试正则表达式匹配...`);
143
-
144
- // 使用正则表达式缓存优化性能
145
- if (!this.regexCache) {
146
- this.regexCache = new Map();
147
- }
148
-
149
- try {
150
- matchedInterface = interfaces.find(intf => {
239
+ if (!methodMatches) {
240
+ continue;
241
+ }
242
+
243
+ // 检查URL是否匹配
244
+ let urlMatches = false;
245
+
246
+ // 精确匹配
247
+ if (intf.urlPattern === requestPath) {
248
+ urlMatches = true;
249
+ } else {
250
+ // 正则表达式匹配
151
251
  try {
152
- // 验证接口对象
153
- if (!intf || !intf.urlPattern) {
154
- return false;
252
+ // 从缓存获取或创建正则表达式
253
+ if (!this.regexCache) {
254
+ this.regexCache = new Map();
155
255
  }
156
256
 
157
- // 从缓存获取或创建正则表达式
158
257
  let regex;
159
258
  if (this.regexCache.has(intf.urlPattern)) {
160
259
  regex = this.regexCache.get(intf.urlPattern);
@@ -166,37 +265,48 @@ const ruleManager = {
166
265
  this.regexCache.set(intf.urlPattern, regex);
167
266
  }
168
267
 
169
- // 获取方法值,兼容不同的字段名
170
- const methodField = intf.httpMethod || intf.method;
171
- const methodValue = methodField && methodField.toUpperCase();
172
-
173
- // 检查URL和方法是否匹配
174
- const urlMatches = regex.test(requestPath);
175
- const methodMatches = !methodValue ||
176
- methodValue === 'ALL' ||
177
- methodValue === 'ANY' ||
178
- methodValue === method;
179
-
180
- return urlMatches && methodMatches;
268
+ urlMatches = regex.test(requestPath);
181
269
  } catch (err) {
182
- // 记录特定接口的错误,但继续处理其他接口
183
- this.log(`[规则处理器] 匹配接口 ${intf?.name || 'unknown'} 时出错: ${err.message}`);
184
- return false;
270
+ this.log(`[规则处理器] 正则匹配接口 ${intf.name} 时出错: ${err.message}`);
271
+ continue;
185
272
  }
186
- });
187
- } catch (err) {
188
- // 记录整体匹配过程的错误
189
- this.log(`[规则处理器] 正则匹配过程出错: ${err.message}`);
190
- return null;
273
+ }
274
+
275
+ if (urlMatches) {
276
+ urlMatchedInterfaces.push(intf);
277
+ }
191
278
  }
192
-
193
- if (matchedInterface) {
194
- this.log(`[规则处理器] 找到正则匹配的接口: ${matchedInterface.name}`);
195
- } else {
279
+
280
+ this.log(`[规则处理器] 找到 ${urlMatchedInterfaces.length} 个URL匹配的接口`);
281
+
282
+ if (urlMatchedInterfaces.length === 0) {
196
283
  this.log(`[规则处理器] 未找到匹配的接口`);
284
+ return null;
285
+ }
286
+
287
+ // 在URL匹配的接口中,查找参数也匹配的接口
288
+ for (const intf of urlMatchedInterfaces) {
289
+ // 检查参数匹配
290
+ if (isParamMatch(req, intf.paramMatchers, this.log)) {
291
+ this.log(`[规则处理器] 找到完全匹配的接口: ${intf.name} (URL + 参数匹配)`);
292
+ return intf;
293
+ } else {
294
+ this.log(`[规则处理器] 接口 ${intf.name} URL匹配但参数不匹配,继续查找...`);
295
+ }
197
296
  }
198
297
 
199
- return matchedInterface;
298
+ // 如果没有参数匹配的接口,返回第一个没有参数匹配规则的接口
299
+ const fallbackInterface = urlMatchedInterfaces.find(intf =>
300
+ !intf.paramMatchers || !Array.isArray(intf.paramMatchers) || intf.paramMatchers.length === 0
301
+ );
302
+
303
+ if (fallbackInterface) {
304
+ this.log(`[规则处理器] 使用回退接口: ${fallbackInterface.name} (无参数匹配规则)`);
305
+ return fallbackInterface;
306
+ }
307
+
308
+ this.log(`[规则处理器] 所有URL匹配的接口都有参数匹配规则且都不满足,未找到合适的接口`);
309
+ return null;
200
310
  },
201
311
 
202
312
  /**
@@ -266,6 +376,11 @@ const ruleManager = {
266
376
  result = await this.handleUrlRedirect(interfaceObj, req, res);
267
377
  }
268
378
  else if (proxyType === 'data_template' || proxyType === 'response') {
379
+ // 添加CORS支持 - 设置跨域相关的响应头
380
+ const origin = req.headers.origin || req.headers.host;
381
+ res.setHeader('Access-Control-Allow-Origin', origin || '*');
382
+ res.setHeader('Access-Control-Allow-Credentials', 'true');
383
+
269
384
  result = await this.handleDataTemplate(interfaceObj, req, res);
270
385
  }
271
386
  else if (proxyType === 'file_proxy' || proxyType === 'file') {
@@ -367,7 +482,29 @@ const ruleManager = {
367
482
  async handleDataTemplate(interfaceObj, req, res) {
368
483
  // 兼容不同的字段命名
369
484
  const config = interfaceObj.config || interfaceObj;
370
- const template = config.responseContent || config.template || '{}';
485
+
486
+ // 支持多响应系统
487
+ let template = '';
488
+
489
+ // 检查是否有多响应配置
490
+ if (config.responses && Array.isArray(config.responses) && config.responses.length > 0) {
491
+ // 获取当前激活的响应
492
+ const activeResponseId = config.activeResponseId;
493
+ const activeResponse = activeResponseId
494
+ ? config.responses.find(r => r.id === activeResponseId)
495
+ : config.responses[0];
496
+
497
+ if (activeResponse) {
498
+ this.log(`[规则处理器] 使用响应: ${activeResponse.name || '未命名'}`);
499
+ template = activeResponse.content;
500
+ }
501
+ }
502
+
503
+ // 如果没有找到响应内容,回退到传统字段
504
+ if (!template) {
505
+ template = config.responseContent || config.template || '{}';
506
+ this.log(`[规则处理器] 使用传统响应内容`);
507
+ }
371
508
 
372
509
  if (!template) {
373
510
  res.end(JSON.stringify({ error: 'No template specified' }));
@@ -385,8 +522,20 @@ const ruleManager = {
385
522
 
386
523
  // 发送数据
387
524
  res.end(JSON.stringify(mockData));
388
- return { mockData };
525
+
526
+ // 返回处理结果,包含响应信息
527
+ return {
528
+ mockData,
529
+ mockInfo: {
530
+ delay: parseInt(config.responseDelay || config.delay || 0, 10),
531
+ timestamp: new Date().toISOString(),
532
+ responseName: config.responses && config.activeResponseId
533
+ ? (config.responses.find(r => r.id === config.activeResponseId)?.name || '未命名')
534
+ : '默认响应'
535
+ }
536
+ };
389
537
  } catch (err) {
538
+ this.log(`[规则处理器] 模板解析错误: ${err.message}`);
390
539
  res.end(JSON.stringify({ error: 'Template parsing error', message: err.message }));
391
540
  return { error: 'Template parsing error', message: err.message };
392
541
  }