json-api-mocker 2.3.1 → 3.0.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/dist/server.d.ts CHANGED
@@ -1,22 +1,21 @@
1
- import { Express } from 'express';
2
- import { Config } from './types';
3
- export declare class MockServer {
4
- private app;
5
- private server;
6
- private wss;
7
- private config;
8
- private configPath;
9
- constructor(config: Config, configPath?: string);
10
- getApp(): Express;
11
- private setupMiddleware;
12
- private logRequest;
13
- private generateMockData;
14
- private handleRequest;
15
- private setupRoutes;
16
- private createRoute;
17
- private findRouteConfig;
18
- private generateMockResponse;
19
- private setupWebSocket;
20
- start(): void;
21
- close(): void;
22
- }
1
+ import type { Config } from './types';
2
+ export declare class MockServer {
3
+ private app;
4
+ private configPath;
5
+ private config;
6
+ private serverConfig;
7
+ private logs;
8
+ private readonly MAX_LOGS;
9
+ private upload;
10
+ private wss;
11
+ private clients;
12
+ constructor(serverConfig?: Config, configPath?: string);
13
+ private loadConfig;
14
+ private saveConfig;
15
+ private setupConfigRoutes;
16
+ private setupMockRoutes;
17
+ private sendResponse;
18
+ private setupUploadRoute;
19
+ start(port?: number): void;
20
+ private broadcastLog;
21
+ }
package/dist/server.js CHANGED
@@ -1,205 +1,328 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.MockServer = void 0;
7
- const mockjs_1 = __importDefault(require("mockjs"));
8
- const express_1 = __importDefault(require("express"));
9
- const cors_1 = __importDefault(require("cors"));
10
- const ws_1 = require("ws");
11
- const http_1 = __importDefault(require("http"));
12
- class MockServer {
13
- constructor(config, configPath = 'data.json') {
14
- this.app = (0, express_1.default)();
15
- this.wss = null;
16
- this.logRequest = (req, res, next) => {
17
- const startTime = Date.now();
18
- const requestId = Math.random().toString(36).substring(7);
19
- console.log(`[${new Date().toISOString()}] Request ${requestId}:`);
20
- console.log(` Method: ${req.method}`);
21
- console.log(` URL: ${req.url}`);
22
- console.log(` Query Params: ${JSON.stringify(req.query)}`);
23
- console.log(` Body: ${JSON.stringify(req.body)}`);
24
- res.on('finish', () => {
25
- const duration = Date.now() - startTime;
26
- console.log(`[${new Date().toISOString()}] Response ${requestId}:`);
27
- console.log(` Status: ${res.statusCode}`);
28
- console.log(` Duration: ${duration}ms`);
29
- console.log('----------------------------------------');
30
- });
31
- next();
32
- };
33
- this.config = config;
34
- this.configPath = configPath;
35
- this.server = http_1.default.createServer(this.app);
36
- this.setupMiddleware();
37
- this.setupRoutes();
38
- if (config.websocket?.enabled) {
39
- this.setupWebSocket();
40
- }
41
- }
42
- getApp() {
43
- return this.app;
44
- }
45
- setupMiddleware() {
46
- this.app.use((0, cors_1.default)());
47
- this.app.use(express_1.default.json());
48
- this.app.use('/uploads', express_1.default.static('uploads'));
49
- this.app.use(this.logRequest);
50
- }
51
- generateMockData(config) {
52
- try {
53
- if (config.mock?.enabled && config.mock.template) {
54
- const { total, template } = config.mock;
55
- return mockjs_1.default.mock({
56
- [`data|${total}`]: [template]
57
- }).data;
58
- }
59
- return config.response;
60
- }
61
- catch (error) {
62
- console.error('Error generating mock data:', error);
63
- return config.response;
64
- }
65
- }
66
- handleRequest(config) {
67
- return (req, res) => {
68
- try {
69
- let responseData = this.generateMockData(config);
70
- if (config.pagination?.enabled && Array.isArray(responseData)) {
71
- const page = parseInt(req.query.page) || 1;
72
- const pageSize = parseInt(req.query.pageSize) || config.pagination.pageSize;
73
- const startIndex = (page - 1) * pageSize;
74
- const endIndex = startIndex + pageSize;
75
- const paginatedData = responseData.slice(startIndex, endIndex);
76
- res.header('X-Total-Count', responseData.length.toString());
77
- responseData = paginatedData;
78
- }
79
- res.json(responseData);
80
- }
81
- catch (error) {
82
- console.error('Error handling request:', error);
83
- res.status(500).json({ error: 'Internal server error' });
84
- }
85
- };
86
- }
87
- setupRoutes() {
88
- this.config.routes.forEach((route) => {
89
- Object.entries(route.methods).forEach(([method, methodConfig]) => {
90
- this.createRoute(route.path, method, methodConfig);
91
- });
92
- });
93
- }
94
- createRoute(path, method, config) {
95
- const fullPath = `${this.config.server.baseProxy}${path}`;
96
- console.log(`创建路由: ${method.toUpperCase()} ${fullPath}`);
97
- switch (method.toLowerCase()) {
98
- case 'get':
99
- this.app.get(fullPath, this.handleRequest(config));
100
- break;
101
- case 'post':
102
- if (path === '/upload/avatar') {
103
- // 对于文件上传路由,使用特殊处理
104
- this.app.post(fullPath, (req, res) => {
105
- const mockResponse = this.generateMockData(config);
106
- res.json(mockResponse);
107
- });
108
- }
109
- else {
110
- this.app.post(fullPath, this.handleRequest(config));
111
- }
112
- break;
113
- case 'put':
114
- this.app.put(`${fullPath}/:id`, this.handleRequest(config));
115
- break;
116
- case 'delete':
117
- this.app.delete(`${fullPath}/:id`, this.handleRequest(config));
118
- break;
119
- }
120
- }
121
- findRouteConfig(path, method) {
122
- const route = this.config.routes.find(r => r.path === path);
123
- return route?.methods[method] || null;
124
- }
125
- generateMockResponse(config) {
126
- if (config.mock?.enabled && config.mock.template) {
127
- return mockjs_1.default.mock(config.mock.template);
128
- }
129
- return config.response;
130
- }
131
- setupWebSocket() {
132
- if (!this.config.websocket)
133
- return;
134
- this.wss = new ws_1.Server({
135
- server: this.server,
136
- path: this.config.websocket.path
137
- });
138
- this.wss.on('connection', (ws) => {
139
- console.log('WebSocket client connected');
140
- // 处理客户端消息
141
- ws.on('message', (message) => {
142
- try {
143
- const data = JSON.parse(message.toString());
144
- const eventConfig = this.config.websocket?.events?.[data.event];
145
- if (eventConfig?.mock.enabled) {
146
- const response = mockjs_1.default.mock(eventConfig.mock.template);
147
- ws.send(JSON.stringify({
148
- event: data.event,
149
- data: response
150
- }));
151
- }
152
- }
153
- catch (error) {
154
- console.error('Error handling WebSocket message:', error);
155
- }
156
- });
157
- // 设置自动发送数据的定时器
158
- if (this.config.websocket && this.config.websocket.events) {
159
- Object.entries(this.config.websocket.events).forEach(([event, config]) => {
160
- if (config.mock.interval) {
161
- setInterval(() => {
162
- const response = mockjs_1.default.mock(config.mock.template);
163
- ws.send(JSON.stringify({
164
- event,
165
- data: response
166
- }));
167
- }, config.mock.interval);
168
- }
169
- });
170
- }
171
- ws.on('close', () => {
172
- // 移除日志,避免测试完成后的日志输出
173
- // console.log('WebSocket client disconnected');
174
- });
175
- });
176
- }
177
- start() {
178
- this.server.listen(this.config.server.port, () => {
179
- console.log(`Mock 服务器已启动:`);
180
- console.log(`- HTTP 地址: http://localhost:${this.config.server.port}`);
181
- if (this.config.websocket?.enabled) {
182
- console.log(`- WebSocket 地址: ws://localhost:${this.config.server.port}${this.config.websocket.path}`);
183
- }
184
- console.log(`- 基础路径: ${this.config.server.baseProxy}`);
185
- console.log('可用的接口:');
186
- this.config.routes.forEach(route => {
187
- Object.keys(route.methods).forEach(method => {
188
- console.log(` ${method.toUpperCase()} http://localhost:${this.config.server.port}${this.config.server.baseProxy}${route.path}`);
189
- });
190
- });
191
- });
192
- }
193
- close() {
194
- // 关闭所有 WebSocket 连接
195
- if (this.wss) {
196
- this.wss.clients.forEach(client => {
197
- client.close();
198
- });
199
- this.wss.close();
200
- }
201
- // 关闭 HTTP 服务器
202
- this.server.close();
203
- }
204
- }
205
- exports.MockServer = MockServer;
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.MockServer = void 0;
7
+ const express_1 = __importDefault(require("express"));
8
+ const cors_1 = __importDefault(require("cors"));
9
+ const fs_1 = require("fs");
10
+ const path_1 = require("path");
11
+ const uuid_1 = require("uuid");
12
+ const mockjs_1 = __importDefault(require("mockjs"));
13
+ const multer_1 = __importDefault(require("multer"));
14
+ const ws_1 = require("ws");
15
+ class MockServer {
16
+ constructor(serverConfig = {}, configPath = 'data.json') {
17
+ this.logs = []; // 存储请求日志
18
+ this.MAX_LOGS = 1000; // 最大日志数量
19
+ this.clients = new Set();
20
+ this.app = (0, express_1.default)();
21
+ this.serverConfig = serverConfig;
22
+ this.configPath = (0, path_1.join)(process.cwd(), configPath);
23
+ this.config = this.loadConfig();
24
+ // 添加跨域支持
25
+ this.app.use((0, cors_1.default)());
26
+ this.app.use(express_1.default.json());
27
+ // 注意:先设置配置管理接口,再设置mock接口
28
+ this.setupConfigRoutes();
29
+ this.setupMockRoutes();
30
+ // 使用内存存储
31
+ this.upload = (0, multer_1.default)({
32
+ storage: multer_1.default.memoryStorage()
33
+ });
34
+ // 添加文件上传路由
35
+ this.setupUploadRoute();
36
+ // 使用固定的 WebSocket 端口
37
+ this.wss = new ws_1.WebSocketServer({ port: serverConfig.wsPort || 88866 });
38
+ this.wss.on('connection', (ws) => {
39
+ this.clients.add(ws);
40
+ ws.send(JSON.stringify({
41
+ type: 'init',
42
+ data: this.logs
43
+ }));
44
+ ws.on('close', () => {
45
+ this.clients.delete(ws);
46
+ });
47
+ });
48
+ }
49
+ loadConfig() {
50
+ try {
51
+ const data = (0, fs_1.readFileSync)(this.configPath, 'utf-8');
52
+ const fullConfig = JSON.parse(data);
53
+ // 确保返回的是数组
54
+ const routes = fullConfig.routes || [];
55
+ // 验每个配置项
56
+ return routes.filter(api => {
57
+ const isValid = api &&
58
+ api.id &&
59
+ api.route &&
60
+ typeof api.route.path === 'string' &&
61
+ api.route.methods &&
62
+ typeof api.route.methods === 'object';
63
+ if (!isValid) {
64
+ console.warn('Filtered out invalid API config:', api);
65
+ }
66
+ return isValid;
67
+ });
68
+ }
69
+ catch (error) {
70
+ console.error('Error loading config:', error);
71
+ return [];
72
+ }
73
+ }
74
+ saveConfig() {
75
+ try {
76
+ const data = (0, fs_1.readFileSync)(this.configPath, 'utf-8');
77
+ const fullConfig = JSON.parse(data);
78
+ // 处理每个 API 的响应数据
79
+ const processedRoutes = this.config.map(api => ({
80
+ ...api,
81
+ route: {
82
+ ...api.route,
83
+ methods: Object.entries(api.route.methods).reduce((acc, [method, config]) => ({
84
+ ...acc,
85
+ [method]: {
86
+ ...config,
87
+ // 解析并重新格式化 JSON,移除多余的转义
88
+ response: typeof config.response === 'string'
89
+ ? JSON.stringify(JSON.parse(config.response))
90
+ : JSON.stringify(config.response),
91
+ headers: config.headers || {}
92
+ }
93
+ }), {})
94
+ }
95
+ }));
96
+ fullConfig.routes = processedRoutes;
97
+ (0, fs_1.writeFileSync)(this.configPath, JSON.stringify(fullConfig, null, 2));
98
+ }
99
+ catch (error) {
100
+ console.error('Error saving config:', error);
101
+ }
102
+ }
103
+ setupConfigRoutes() {
104
+ const baseProxy = this.serverConfig.baseProxy || '';
105
+ // 获取所有API配置
106
+ this.app.get('/api/_config', (req, res) => {
107
+ console.log('Sending config:', this.config);
108
+ res.json(this.config);
109
+ });
110
+ // 创建新API配置
111
+ this.app.post('/api/_config', (req, res) => {
112
+ const newApi = {
113
+ id: (0, uuid_1.v4)(),
114
+ route: req.body.route
115
+ };
116
+ this.config.push(newApi);
117
+ this.saveConfig();
118
+ res.json(newApi);
119
+ });
120
+ // 更新API配置
121
+ this.app.put('/api/_config/:id', (req, res) => {
122
+ const index = this.config.findIndex(api => api.id === req.params.id);
123
+ if (index === -1) {
124
+ res.status(404).json({ error: 'API not found' });
125
+ return;
126
+ }
127
+ this.config[index] = {
128
+ id: req.params.id,
129
+ route: req.body.route
130
+ };
131
+ this.saveConfig();
132
+ res.json(this.config[index]);
133
+ });
134
+ // 删除API配置
135
+ this.app.delete('/api/_config/:id', (req, res) => {
136
+ const index = this.config.findIndex(api => api.id === req.params.id);
137
+ if (index === -1) {
138
+ res.status(404).json({ error: 'API not found' });
139
+ return;
140
+ }
141
+ this.config.splice(index, 1);
142
+ this.saveConfig();
143
+ res.status(204).send();
144
+ });
145
+ // 添加日志接口
146
+ this.app.get('/api/_logs', (req, res) => {
147
+ const { page = 1, size = 20 } = req.query;
148
+ const start = (Number(page) - 1) * Number(size);
149
+ const end = start + Number(size);
150
+ const total = this.logs.length;
151
+ res.json({
152
+ total,
153
+ list: this.logs.slice(start, end)
154
+ });
155
+ });
156
+ // 清除日志
157
+ this.app.delete('/api/_logs', (req, res) => {
158
+ this.logs = [];
159
+ res.status(204).send();
160
+ });
161
+ }
162
+ setupMockRoutes() {
163
+ const baseProxy = this.serverConfig.baseProxy || '';
164
+ this.app.all('*', (req, res, next) => {
165
+ // 如果是配置接口,跳过日志记录
166
+ if (req.path === '/api/_config' || req.path.startsWith('/api/_config/') ||
167
+ req.path === '/api/_logs' || req.path.startsWith('/api/_logs/')) {
168
+ return next();
169
+ }
170
+ const startTime = Date.now();
171
+ const originalSend = res.send;
172
+ // 修复 this 指向问题
173
+ const self = this;
174
+ // 记录请求日志
175
+ res.send = function (body) {
176
+ const endTime = Date.now();
177
+ const duration = endTime - startTime;
178
+ const log = {
179
+ id: (0, uuid_1.v4)(),
180
+ path: req.path,
181
+ method: req.method,
182
+ timestamp: new Date().toISOString(),
183
+ status: res.statusCode,
184
+ duration,
185
+ params: {
186
+ query: req.query,
187
+ body: req.body,
188
+ params: req.params
189
+ },
190
+ requestBody: req.body,
191
+ responseBody: body
192
+ };
193
+ // 使用正确的 this 引用
194
+ self.logs.unshift(log);
195
+ if (self.logs.length > self.MAX_LOGS) {
196
+ self.logs.pop();
197
+ }
198
+ // 广播新日志
199
+ self.broadcastLog(log);
200
+ return originalSend.call(this, body);
201
+ };
202
+ next();
203
+ });
204
+ // 处理所有mock请求,但排除配置接口
205
+ this.app.all('*', (req, res, next) => {
206
+ try {
207
+ // 如果是配置接口,跳过这个中间件
208
+ if (req.path === '/api/_config' || req.path.startsWith('/api/_config/')) {
209
+ return next();
210
+ }
211
+ console.log('Received request for path:', req.path);
212
+ console.log('Current config:', this.config);
213
+ if (!Array.isArray(this.config)) {
214
+ console.error('Config is not an array:', this.config);
215
+ res.status(500).json({ error: 'Internal server error' });
216
+ return;
217
+ }
218
+ const api = this.config.find(api => {
219
+ if (!api || !api.route || typeof api.route.path !== 'string') {
220
+ console.error('Invalid API config:', api);
221
+ return false;
222
+ }
223
+ // 移除 baseProxy 前缀再比较
224
+ const requestPath = req.path.replace(baseProxy, '');
225
+ return api.route.path === requestPath;
226
+ });
227
+ if (!api) {
228
+ res.status(404).json({ error: 'API not found' });
229
+ return;
230
+ }
231
+ if (!api.route || !api.route.methods) {
232
+ res.status(500).json({ error: 'Invalid API configuration' });
233
+ return;
234
+ }
235
+ const method = req.method.toLowerCase();
236
+ const methodConfig = api.route.methods[method];
237
+ if (!methodConfig) {
238
+ res.status(405).json({ error: 'Method not allowed' });
239
+ return;
240
+ }
241
+ if (methodConfig.delay) {
242
+ setTimeout(() => {
243
+ this.sendResponse(res, methodConfig);
244
+ }, methodConfig.delay);
245
+ }
246
+ else {
247
+ this.sendResponse(res, methodConfig);
248
+ }
249
+ }
250
+ catch (error) {
251
+ console.error('Error handling request:', error);
252
+ res.status(500).json({ error: 'Internal server error' });
253
+ }
254
+ });
255
+ }
256
+ sendResponse(res, config) {
257
+ try {
258
+ // 设置响应头
259
+ if (config.headers) {
260
+ Object.entries(config.headers).forEach(([key, value]) => {
261
+ res.setHeader(key, value);
262
+ });
263
+ }
264
+ // 处理响应数据
265
+ let responseData = config.response;
266
+ if (typeof responseData === 'string') {
267
+ try {
268
+ responseData = JSON.parse(responseData);
269
+ }
270
+ catch (e) {
271
+ console.error('Failed to parse response string:', e);
272
+ responseData = { error: 'Invalid response format' };
273
+ }
274
+ }
275
+ // 使用 Mock.js 处理数据
276
+ const mockedData = mockjs_1.default.mock(responseData);
277
+ res.status(config.status || 200).json(mockedData);
278
+ }
279
+ catch (error) {
280
+ console.error('Error processing response:', error);
281
+ res.status(500).json({
282
+ error: 'Internal server error',
283
+ details: error instanceof Error ? error.message : 'Unknown error'
284
+ });
285
+ }
286
+ }
287
+ setupUploadRoute() {
288
+ // 处理文件上传
289
+ this.app.post('/api/upload', this.upload.single('file'), (req, res) => {
290
+ if (!req.file) {
291
+ return res.status(400).json({
292
+ code: 400,
293
+ message: 'No file uploaded',
294
+ data: null
295
+ });
296
+ }
297
+ // 只返回模拟数据,不保存文件
298
+ res.json({
299
+ code: 200,
300
+ message: 'success',
301
+ data: {
302
+ url: mockjs_1.default.Random.image('200x200'),
303
+ filename: req.file.originalname,
304
+ size: req.file.size
305
+ }
306
+ });
307
+ });
308
+ }
309
+ start(port) {
310
+ const serverPort = port || this.serverConfig.port || 3000;
311
+ this.app.listen(serverPort, () => {
312
+ console.log(`Mock server is running on http://localhost:${serverPort}`);
313
+ });
314
+ }
315
+ // 广播日志给所有客户端
316
+ broadcastLog(log) {
317
+ const message = JSON.stringify({
318
+ type: 'log',
319
+ data: log
320
+ });
321
+ this.clients.forEach(client => {
322
+ if (client.readyState === ws_1.WebSocket.OPEN) {
323
+ client.send(message);
324
+ }
325
+ });
326
+ }
327
+ }
328
+ exports.MockServer = MockServer;