json-api-mocker 2.2.2 → 2.3.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.
package/dist/server.d.ts CHANGED
@@ -1,21 +1,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
- }
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
+ }
package/dist/server.js CHANGED
@@ -1,325 +1,205 @@
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 path_2 = __importDefault(require("path"));
15
- const ws_1 = require("ws");
16
- class MockServer {
17
- constructor(serverConfig = {}, configPath = 'data.json') {
18
- this.logs = []; // 存储请求日志
19
- this.MAX_LOGS = 1000; // 最大日志数量
20
- this.clients = new Set();
21
- this.app = (0, express_1.default)();
22
- this.serverConfig = serverConfig;
23
- this.configPath = (0, path_1.join)(process.cwd(), configPath);
24
- this.config = this.loadConfig();
25
- // 添加跨域支持
26
- this.app.use((0, cors_1.default)());
27
- this.app.use(express_1.default.json());
28
- // 注意:先设置配置管理接口,再设置mock接口
29
- this.setupConfigRoutes();
30
- this.setupMockRoutes();
31
- // 配置文件上传
32
- const storage = multer_1.default.diskStorage({
33
- destination: (req, file, cb) => {
34
- const uploadDir = path_2.default.join(process.cwd(), 'uploads');
35
- cb(null, uploadDir);
36
- },
37
- filename: (req, file, cb) => {
38
- // 生成唯一文件名
39
- const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
40
- cb(null, file.fieldname + '-' + uniqueSuffix + path_2.default.extname(file.originalname));
41
- }
42
- });
43
- this.upload = (0, multer_1.default)({ storage });
44
- // 添加文件上传路由
45
- this.setupUploadRoute();
46
- // 使用固定的 WebSocket 端口
47
- this.wss = new ws_1.WebSocketServer({ port: serverConfig.wsPort || 88866 });
48
- this.wss.on('connection', (ws) => {
49
- this.clients.add(ws);
50
- ws.send(JSON.stringify({
51
- type: 'init',
52
- data: this.logs
53
- }));
54
- ws.on('close', () => {
55
- this.clients.delete(ws);
56
- });
57
- });
58
- }
59
- loadConfig() {
60
- try {
61
- const data = (0, fs_1.readFileSync)(this.configPath, 'utf-8');
62
- const fullConfig = JSON.parse(data);
63
- // 确保返回的是数组
64
- const routes = fullConfig.routes || [];
65
- // 验每个配置项
66
- return routes.filter(api => {
67
- const isValid = api &&
68
- api.id &&
69
- api.route &&
70
- typeof api.route.path === 'string' &&
71
- api.route.methods &&
72
- typeof api.route.methods === 'object';
73
- if (!isValid) {
74
- console.warn('Filtered out invalid API config:', api);
75
- }
76
- return isValid;
77
- });
78
- }
79
- catch (error) {
80
- console.error('Error loading config:', error);
81
- return [];
82
- }
83
- }
84
- saveConfig() {
85
- try {
86
- const data = (0, fs_1.readFileSync)(this.configPath, 'utf-8');
87
- const fullConfig = JSON.parse(data);
88
- // 处理每个 API 的响应数据
89
- const processedRoutes = this.config.map(api => ({
90
- ...api,
91
- route: {
92
- ...api.route,
93
- methods: Object.entries(api.route.methods).reduce((acc, [method, config]) => ({
94
- ...acc,
95
- [method]: {
96
- ...config,
97
- // 解析并重新格式化 JSON,移除多余的转义
98
- response: typeof config.response === 'string'
99
- ? JSON.stringify(JSON.parse(config.response))
100
- : JSON.stringify(config.response),
101
- headers: config.headers || {}
102
- }
103
- }), {})
104
- }
105
- }));
106
- fullConfig.routes = processedRoutes;
107
- (0, fs_1.writeFileSync)(this.configPath, JSON.stringify(fullConfig, null, 2));
108
- }
109
- catch (error) {
110
- console.error('Error saving config:', error);
111
- }
112
- }
113
- setupConfigRoutes() {
114
- const baseProxy = this.serverConfig.baseProxy || '';
115
- // 获取所有API配置
116
- this.app.get('/api/_config', (req, res) => {
117
- console.log('Sending config:', this.config);
118
- res.json(this.config);
119
- });
120
- // 创建新API配置
121
- this.app.post('/api/_config', (req, res) => {
122
- const newApi = {
123
- id: (0, uuid_1.v4)(),
124
- route: req.body.route
125
- };
126
- this.config.push(newApi);
127
- this.saveConfig();
128
- res.json(newApi);
129
- });
130
- // 更新API配置
131
- this.app.put('/api/_config/:id', (req, res) => {
132
- const index = this.config.findIndex(api => api.id === req.params.id);
133
- if (index === -1) {
134
- res.status(404).json({ error: 'API not found' });
135
- return;
136
- }
137
- this.config[index] = {
138
- id: req.params.id,
139
- route: req.body.route
140
- };
141
- this.saveConfig();
142
- res.json(this.config[index]);
143
- });
144
- // 删除API配置
145
- this.app.delete('/api/_config/:id', (req, res) => {
146
- const index = this.config.findIndex(api => api.id === req.params.id);
147
- if (index === -1) {
148
- res.status(404).json({ error: 'API not found' });
149
- return;
150
- }
151
- this.config.splice(index, 1);
152
- this.saveConfig();
153
- res.status(204).send();
154
- });
155
- // 添加日志接口
156
- this.app.get('/api/_logs', (req, res) => {
157
- const { page = 1, size = 20 } = req.query;
158
- const start = (Number(page) - 1) * Number(size);
159
- const end = start + Number(size);
160
- const total = this.logs.length;
161
- res.json({
162
- total,
163
- list: this.logs.slice(start, end)
164
- });
165
- });
166
- // 清除日志
167
- this.app.delete('/api/_logs', (req, res) => {
168
- this.logs = [];
169
- res.status(204).send();
170
- });
171
- }
172
- setupMockRoutes() {
173
- const baseProxy = this.serverConfig.baseProxy || '';
174
- this.app.all('*', (req, res, next) => {
175
- // 如果是配置接口,跳过日志记录
176
- if (req.path === '/api/_config' || req.path.startsWith('/api/_config/') ||
177
- req.path === '/api/_logs' || req.path.startsWith('/api/_logs/')) {
178
- return next();
179
- }
180
- const startTime = Date.now();
181
- const originalSend = res.send;
182
- // 修复 this 指向问题
183
- const self = this;
184
- // 记录请求日志
185
- res.send = function (body) {
186
- const endTime = Date.now();
187
- const duration = endTime - startTime;
188
- const log = {
189
- id: (0, uuid_1.v4)(),
190
- path: req.path,
191
- method: req.method,
192
- timestamp: new Date().toISOString(),
193
- status: res.statusCode,
194
- duration,
195
- params: {
196
- query: req.query,
197
- body: req.body,
198
- params: req.params
199
- },
200
- requestBody: req.body,
201
- responseBody: body
202
- };
203
- // 使用正确的 this 引用
204
- self.logs.unshift(log);
205
- if (self.logs.length > self.MAX_LOGS) {
206
- self.logs.pop();
207
- }
208
- // 广播新日志
209
- self.broadcastLog(log);
210
- return originalSend.call(this, body);
211
- };
212
- next();
213
- });
214
- // 处理所有mock请求,但排除配置接口
215
- this.app.all('*', (req, res, next) => {
216
- try {
217
- // 如果是配置接口,跳过这个中间件
218
- if (req.path === '/api/_config' || req.path.startsWith('/api/_config/')) {
219
- return next();
220
- }
221
- console.log('Received request for path:', req.path);
222
- console.log('Current config:', this.config);
223
- if (!Array.isArray(this.config)) {
224
- console.error('Config is not an array:', this.config);
225
- res.status(500).json({ error: 'Internal server error' });
226
- return;
227
- }
228
- const api = this.config.find(api => {
229
- if (!api || !api.route || typeof api.route.path !== 'string') {
230
- console.error('Invalid API config:', api);
231
- return false;
232
- }
233
- // 移除 baseProxy 前缀再比较
234
- const requestPath = req.path.replace(baseProxy, '');
235
- return api.route.path === requestPath;
236
- });
237
- if (!api) {
238
- res.status(404).json({ error: 'API not found' });
239
- return;
240
- }
241
- if (!api.route || !api.route.methods) {
242
- res.status(500).json({ error: 'Invalid API configuration' });
243
- return;
244
- }
245
- const method = req.method.toLowerCase();
246
- const methodConfig = api.route.methods[method];
247
- if (!methodConfig) {
248
- res.status(405).json({ error: 'Method not allowed' });
249
- return;
250
- }
251
- if (methodConfig.delay) {
252
- setTimeout(() => {
253
- this.sendResponse(res, methodConfig);
254
- }, methodConfig.delay);
255
- }
256
- else {
257
- this.sendResponse(res, methodConfig);
258
- }
259
- }
260
- catch (error) {
261
- console.error('Error handling request:', error);
262
- res.status(500).json({ error: 'Internal server error' });
263
- }
264
- });
265
- }
266
- sendResponse(res, config) {
267
- try {
268
- if (config.headers) {
269
- Object.entries(config.headers).forEach(([key, value]) => {
270
- res.setHeader(key, value);
271
- });
272
- }
273
- // 解析存储的响应数据
274
- let responseData = typeof config.response === 'string'
275
- ? JSON.parse(config.response.replace(/\\/g, '')) // 移除多余的反斜杠
276
- : config.response;
277
- // 使用 Mock.js 处理数据
278
- const mockedData = mockjs_1.default.mock(responseData);
279
- res.status(config.status || 200).json(mockedData);
280
- }
281
- catch (error) {
282
- console.error('Error processing response:', error);
283
- res.status(500).json({ error: 'Internal server error' });
284
- }
285
- }
286
- setupUploadRoute() {
287
- // 处理文件上传
288
- this.app.post('/api/upload', this.upload.single('file'), (req, res) => {
289
- if (!req.file) {
290
- return res.status(400).json({ error: 'No file uploaded' });
291
- }
292
- // 返回文件URL
293
- const fileUrl = `/uploads/${req.file.filename}`;
294
- res.json({
295
- success: true,
296
- data: {
297
- url: fileUrl,
298
- filename: req.file.originalname,
299
- size: req.file.size
300
- }
301
- });
302
- });
303
- // 提供静态文件访问
304
- this.app.use('/uploads', express_1.default.static(path_2.default.join(process.cwd(), 'uploads')));
305
- }
306
- start(port) {
307
- const serverPort = port || this.serverConfig.port || 3000;
308
- this.app.listen(serverPort, () => {
309
- console.log(`Mock server is running on http://localhost:${serverPort}`);
310
- });
311
- }
312
- // 广播日志给所有客户端
313
- broadcastLog(log) {
314
- const message = JSON.stringify({
315
- type: 'log',
316
- data: log
317
- });
318
- this.clients.forEach(client => {
319
- if (client.readyState === ws_1.WebSocket.OPEN) {
320
- client.send(message);
321
- }
322
- });
323
- }
324
- }
325
- 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 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;