json-api-mocker 1.2.6 → 2.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.js CHANGED
@@ -1,140 +1,326 @@
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 multer_1 = __importDefault(require("multer"));
11
- class MockServer {
12
- constructor(config, configPath = 'data.json') {
13
- this.app = (0, express_1.default)();
14
- this.logRequest = (req, res, next) => {
15
- const startTime = Date.now();
16
- const requestId = Math.random().toString(36).substring(7);
17
- console.log(`[${new Date().toISOString()}] Request ${requestId}:`);
18
- console.log(` Method: ${req.method}`);
19
- console.log(` URL: ${req.url}`);
20
- console.log(` Query Params: ${JSON.stringify(req.query)}`);
21
- console.log(` Body: ${JSON.stringify(req.body)}`);
22
- res.on('finish', () => {
23
- const duration = Date.now() - startTime;
24
- console.log(`[${new Date().toISOString()}] Response ${requestId}:`);
25
- console.log(` Status: ${res.statusCode}`);
26
- console.log(` Duration: ${duration}ms`);
27
- console.log('----------------------------------------');
28
- });
29
- next();
30
- };
31
- this.config = config;
32
- this.configPath = configPath;
33
- this.setupMiddleware();
34
- this.setupFileUpload();
35
- this.setupRoutes();
36
- }
37
- setupMiddleware() {
38
- this.app.use((0, cors_1.default)());
39
- this.app.use(express_1.default.json());
40
- this.app.use('/uploads', express_1.default.static('uploads'));
41
- this.app.use(this.logRequest);
42
- }
43
- generateMockData(config) {
44
- try {
45
- if (config.mock?.enabled && config.mock.template) {
46
- const { total, template } = config.mock;
47
- return mockjs_1.default.mock({
48
- [`data|${total}`]: [template]
49
- }).data;
50
- }
51
- return config.response;
52
- }
53
- catch (error) {
54
- console.error('Error generating mock data:', error);
55
- return config.response;
56
- }
57
- }
58
- handleRequest(config) {
59
- return (req, res) => {
60
- try {
61
- let responseData = this.generateMockData(config);
62
- if (config.pagination?.enabled && Array.isArray(responseData)) {
63
- const page = parseInt(req.query.page) || 1;
64
- const pageSize = parseInt(req.query.pageSize) || config.pagination.pageSize;
65
- const startIndex = (page - 1) * pageSize;
66
- const endIndex = startIndex + pageSize;
67
- const paginatedData = responseData.slice(startIndex, endIndex);
68
- res.header('X-Total-Count', responseData.length.toString());
69
- responseData = paginatedData;
70
- }
71
- res.json(responseData);
72
- }
73
- catch (error) {
74
- console.error('Error handling request:', error);
75
- res.status(500).json({ error: 'Internal server error' });
76
- }
77
- };
78
- }
79
- setupRoutes() {
80
- this.config.routes.forEach((route) => {
81
- Object.entries(route.methods).forEach(([method, methodConfig]) => {
82
- this.createRoute(route.path, method, methodConfig);
83
- });
84
- });
85
- }
86
- createRoute(path, method, config) {
87
- const fullPath = `${this.config.server.baseProxy}${path}`;
88
- console.log(`创建路由: ${method.toUpperCase()} ${fullPath}`);
89
- switch (method.toLowerCase()) {
90
- case 'get':
91
- this.app.get(fullPath, this.handleRequest(config));
92
- break;
93
- case 'post':
94
- this.app.post(fullPath, this.handleRequest(config));
95
- break;
96
- case 'put':
97
- this.app.put(`${fullPath}/:id`, this.handleRequest(config));
98
- break;
99
- case 'delete':
100
- this.app.delete(`${fullPath}/:id`, this.handleRequest(config));
101
- break;
102
- }
103
- }
104
- setupFileUpload() {
105
- const upload = (0, multer_1.default)({ storage: multer_1.default.memoryStorage() });
106
- this.app.post('/api/upload/avatar', upload.single('avatar'), (req, res) => {
107
- const config = this.findRouteConfig('/upload/avatar', 'post');
108
- if (!config) {
109
- return res.status(404).json({ error: 'Route not found' });
110
- }
111
- const mockResponse = this.generateMockResponse(config);
112
- res.json(mockResponse);
113
- });
114
- // 多文件上传的处理可以类似实现
115
- }
116
- findRouteConfig(path, method) {
117
- const route = this.config.routes.find(r => r.path === path);
118
- return route?.methods[method] || null;
119
- }
120
- generateMockResponse(config) {
121
- if (config.mock?.enabled && config.mock.template) {
122
- return mockjs_1.default.mock(config.mock.template);
123
- }
124
- return config.response;
125
- }
126
- start() {
127
- this.app.listen(this.config.server.port, () => {
128
- console.log(`Mock 服务器已启动:`);
129
- console.log(`- 地址: http://localhost:${this.config.server.port}`);
130
- console.log(`- 基础路径: ${this.config.server.baseProxy}`);
131
- console.log('可用的接口:');
132
- this.config.routes.forEach(route => {
133
- Object.keys(route.methods).forEach(method => {
134
- console.log(` ${method.toUpperCase()} http://localhost:${this.config.server.port}${this.config.server.baseProxy}${route.path}`);
135
- });
136
- });
137
- });
138
- }
139
- }
140
- 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 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: 8081 });
48
+ this.wss.on('connection', (ws) => {
49
+ this.clients.add(ws);
50
+ // 发送现有日志
51
+ ws.send(JSON.stringify({
52
+ type: 'init',
53
+ data: this.logs
54
+ }));
55
+ ws.on('close', () => {
56
+ this.clients.delete(ws);
57
+ });
58
+ });
59
+ }
60
+ loadConfig() {
61
+ try {
62
+ const data = (0, fs_1.readFileSync)(this.configPath, 'utf-8');
63
+ const fullConfig = JSON.parse(data);
64
+ // 确保返回的是数组
65
+ const routes = fullConfig.routes || [];
66
+ // 验每个配置项
67
+ return routes.filter(api => {
68
+ const isValid = api &&
69
+ api.id &&
70
+ api.route &&
71
+ typeof api.route.path === 'string' &&
72
+ api.route.methods &&
73
+ typeof api.route.methods === 'object';
74
+ if (!isValid) {
75
+ console.warn('Filtered out invalid API config:', api);
76
+ }
77
+ return isValid;
78
+ });
79
+ }
80
+ catch (error) {
81
+ console.error('Error loading config:', error);
82
+ return [];
83
+ }
84
+ }
85
+ saveConfig() {
86
+ try {
87
+ const data = (0, fs_1.readFileSync)(this.configPath, 'utf-8');
88
+ const fullConfig = JSON.parse(data);
89
+ // 处理每个 API 的响应数据
90
+ const processedRoutes = this.config.map(api => ({
91
+ ...api,
92
+ route: {
93
+ ...api.route,
94
+ methods: Object.entries(api.route.methods).reduce((acc, [method, config]) => ({
95
+ ...acc,
96
+ [method]: {
97
+ ...config,
98
+ // 解析并重新格式化 JSON,移除多余的转义
99
+ response: typeof config.response === 'string'
100
+ ? JSON.stringify(JSON.parse(config.response))
101
+ : JSON.stringify(config.response),
102
+ headers: config.headers || {}
103
+ }
104
+ }), {})
105
+ }
106
+ }));
107
+ fullConfig.routes = processedRoutes;
108
+ (0, fs_1.writeFileSync)(this.configPath, JSON.stringify(fullConfig, null, 2));
109
+ }
110
+ catch (error) {
111
+ console.error('Error saving config:', error);
112
+ }
113
+ }
114
+ setupConfigRoutes() {
115
+ const baseProxy = this.serverConfig.baseProxy || '';
116
+ // 获取所有API配置
117
+ this.app.get('/api/_config', (req, res) => {
118
+ console.log('Sending config:', this.config);
119
+ res.json(this.config);
120
+ });
121
+ // 创建新API配置
122
+ this.app.post('/api/_config', (req, res) => {
123
+ const newApi = {
124
+ id: (0, uuid_1.v4)(),
125
+ route: req.body.route
126
+ };
127
+ this.config.push(newApi);
128
+ this.saveConfig();
129
+ res.json(newApi);
130
+ });
131
+ // 更新API配置
132
+ this.app.put('/api/_config/:id', (req, res) => {
133
+ const index = this.config.findIndex(api => api.id === req.params.id);
134
+ if (index === -1) {
135
+ res.status(404).json({ error: 'API not found' });
136
+ return;
137
+ }
138
+ this.config[index] = {
139
+ id: req.params.id,
140
+ route: req.body.route
141
+ };
142
+ this.saveConfig();
143
+ res.json(this.config[index]);
144
+ });
145
+ // 删除API配置
146
+ this.app.delete('/api/_config/:id', (req, res) => {
147
+ const index = this.config.findIndex(api => api.id === req.params.id);
148
+ if (index === -1) {
149
+ res.status(404).json({ error: 'API not found' });
150
+ return;
151
+ }
152
+ this.config.splice(index, 1);
153
+ this.saveConfig();
154
+ res.status(204).send();
155
+ });
156
+ // 添加日志接口
157
+ this.app.get('/api/_logs', (req, res) => {
158
+ const { page = 1, size = 20 } = req.query;
159
+ const start = (Number(page) - 1) * Number(size);
160
+ const end = start + Number(size);
161
+ const total = this.logs.length;
162
+ res.json({
163
+ total,
164
+ list: this.logs.slice(start, end)
165
+ });
166
+ });
167
+ // 清除日志
168
+ this.app.delete('/api/_logs', (req, res) => {
169
+ this.logs = [];
170
+ res.status(204).send();
171
+ });
172
+ }
173
+ setupMockRoutes() {
174
+ const baseProxy = this.serverConfig.baseProxy || '';
175
+ this.app.all('*', (req, res, next) => {
176
+ // 如果是配置接口,跳过日志记录
177
+ if (req.path === '/api/_config' || req.path.startsWith('/api/_config/') ||
178
+ req.path === '/api/_logs' || req.path.startsWith('/api/_logs/')) {
179
+ return next();
180
+ }
181
+ const startTime = Date.now();
182
+ const originalSend = res.send;
183
+ // 修复 this 指向问题
184
+ const self = this;
185
+ // 记录请求日志
186
+ res.send = function (body) {
187
+ const endTime = Date.now();
188
+ const duration = endTime - startTime;
189
+ const log = {
190
+ id: (0, uuid_1.v4)(),
191
+ path: req.path,
192
+ method: req.method,
193
+ timestamp: new Date().toISOString(),
194
+ status: res.statusCode,
195
+ duration,
196
+ params: {
197
+ query: req.query,
198
+ body: req.body,
199
+ params: req.params
200
+ },
201
+ requestBody: req.body,
202
+ responseBody: body
203
+ };
204
+ // 使用正确的 this 引用
205
+ self.logs.unshift(log);
206
+ if (self.logs.length > self.MAX_LOGS) {
207
+ self.logs.pop();
208
+ }
209
+ // 广播新日志
210
+ self.broadcastLog(log);
211
+ return originalSend.call(this, body);
212
+ };
213
+ next();
214
+ });
215
+ // 处理所有mock请求,但排除配置接口
216
+ this.app.all('*', (req, res, next) => {
217
+ try {
218
+ // 如果是配置接口,跳过这个中间件
219
+ if (req.path === '/api/_config' || req.path.startsWith('/api/_config/')) {
220
+ return next();
221
+ }
222
+ console.log('Received request for path:', req.path);
223
+ console.log('Current config:', this.config);
224
+ if (!Array.isArray(this.config)) {
225
+ console.error('Config is not an array:', this.config);
226
+ res.status(500).json({ error: 'Internal server error' });
227
+ return;
228
+ }
229
+ const api = this.config.find(api => {
230
+ if (!api || !api.route || typeof api.route.path !== 'string') {
231
+ console.error('Invalid API config:', api);
232
+ return false;
233
+ }
234
+ // 移除 baseProxy 前缀再比较
235
+ const requestPath = req.path.replace(baseProxy, '');
236
+ return api.route.path === requestPath;
237
+ });
238
+ if (!api) {
239
+ res.status(404).json({ error: 'API not found' });
240
+ return;
241
+ }
242
+ if (!api.route || !api.route.methods) {
243
+ res.status(500).json({ error: 'Invalid API configuration' });
244
+ return;
245
+ }
246
+ const method = req.method.toLowerCase();
247
+ const methodConfig = api.route.methods[method];
248
+ if (!methodConfig) {
249
+ res.status(405).json({ error: 'Method not allowed' });
250
+ return;
251
+ }
252
+ if (methodConfig.delay) {
253
+ setTimeout(() => {
254
+ this.sendResponse(res, methodConfig);
255
+ }, methodConfig.delay);
256
+ }
257
+ else {
258
+ this.sendResponse(res, methodConfig);
259
+ }
260
+ }
261
+ catch (error) {
262
+ console.error('Error handling request:', error);
263
+ res.status(500).json({ error: 'Internal server error' });
264
+ }
265
+ });
266
+ }
267
+ sendResponse(res, config) {
268
+ try {
269
+ if (config.headers) {
270
+ Object.entries(config.headers).forEach(([key, value]) => {
271
+ res.setHeader(key, value);
272
+ });
273
+ }
274
+ // 解析存储的响应数据
275
+ let responseData = typeof config.response === 'string'
276
+ ? JSON.parse(config.response.replace(/\\/g, '')) // 移除多余的反斜杠
277
+ : config.response;
278
+ // 使用 Mock.js 处理数据
279
+ const mockedData = mockjs_1.default.mock(responseData);
280
+ res.status(config.status || 200).json(mockedData);
281
+ }
282
+ catch (error) {
283
+ console.error('Error processing response:', error);
284
+ res.status(500).json({ error: 'Internal server error' });
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({ error: 'No file uploaded' });
292
+ }
293
+ // 返回文件URL
294
+ const fileUrl = `/uploads/${req.file.filename}`;
295
+ res.json({
296
+ success: true,
297
+ data: {
298
+ url: fileUrl,
299
+ filename: req.file.originalname,
300
+ size: req.file.size
301
+ }
302
+ });
303
+ });
304
+ // 提供静态文件访问
305
+ this.app.use('/uploads', express_1.default.static(path_2.default.join(process.cwd(), 'uploads')));
306
+ }
307
+ start(port) {
308
+ const serverPort = port || this.serverConfig.port || 3000;
309
+ this.app.listen(serverPort, () => {
310
+ console.log(`Mock server is running on http://localhost:${serverPort}`);
311
+ });
312
+ }
313
+ // 广播日志给所有客户端
314
+ broadcastLog(log) {
315
+ const message = JSON.stringify({
316
+ type: 'log',
317
+ data: log
318
+ });
319
+ this.clients.forEach(client => {
320
+ if (client.readyState === ws_1.WebSocket.OPEN) {
321
+ client.send(message);
322
+ }
323
+ });
324
+ }
325
+ }
326
+ exports.MockServer = MockServer;
package/dist/types.d.ts CHANGED
@@ -1,31 +1,35 @@
1
- export interface ServerConfig {
2
- port: number;
3
- baseProxy: string;
4
- }
5
- export interface PaginationConfig {
6
- enabled: boolean;
7
- pageSize: number;
8
- totalCount: number;
9
- }
10
- export interface MockConfig {
11
- enabled: boolean;
12
- total: number;
13
- template: Record<string, any>;
14
- }
15
- export interface MethodConfig {
16
- type?: 'array' | 'object';
17
- response?: any;
18
- mock?: MockConfig;
19
- pagination?: PaginationConfig;
20
- requestSchema?: Record<string, string>;
21
- }
22
- export interface RouteConfig {
23
- path: string;
24
- methods: {
25
- [key: string]: MethodConfig;
26
- };
27
- }
28
- export interface Config {
29
- server: ServerConfig;
30
- routes: RouteConfig[];
31
- }
1
+ export interface MethodConfig {
2
+ status?: number;
3
+ response: any;
4
+ headers?: Record<string, string>;
5
+ delay?: number;
6
+ }
7
+ export interface RouteConfig {
8
+ path: string;
9
+ methods: {
10
+ [key: string]: MethodConfig;
11
+ };
12
+ }
13
+ export interface ApiConfig {
14
+ id: string;
15
+ route: RouteConfig;
16
+ }
17
+ export interface RequestLog {
18
+ id: string;
19
+ path: string;
20
+ method: string;
21
+ timestamp: string;
22
+ status: number;
23
+ duration: number;
24
+ params: {
25
+ query: any;
26
+ body: any;
27
+ params: any;
28
+ };
29
+ requestBody?: any;
30
+ responseBody?: any;
31
+ }
32
+ export interface Config {
33
+ port?: number;
34
+ baseProxy?: string;
35
+ }
package/dist/types.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "json-api-mocker",
3
- "version": "1.2.6",
4
- "description": "A mock server based on JSON configuration",
3
+ "version": "2.0.0",
4
+ "description": "A mock server with web UI",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "bin": {
@@ -9,17 +9,13 @@
9
9
  },
10
10
  "files": [
11
11
  "dist",
12
- "README.md",
13
- "README.ch.md",
14
- "CONFIG.md",
15
- "CONFIG.ch.md"
12
+ "web",
13
+ "README.md"
16
14
  ],
17
15
  "scripts": {
18
16
  "dev": "nodemon",
19
- "build": "tsc",
20
- "start": "node dist/index.js",
21
- "test": "jest",
22
- "prepublishOnly": "npm run build"
17
+ "build": "tsc && pnpm copy-web",
18
+ "copy-web": "rimraf web && mkdir web && node scripts/copy-web.js"
23
19
  },
24
20
  "keywords": [
25
21
  "mock",
@@ -42,20 +38,33 @@
42
38
  },
43
39
  "homepage": "https://github.com/Selteve/json-api-mocker#readme",
44
40
  "dependencies": {
41
+ "commander": "^8.3.0",
45
42
  "cors": "^2.8.5",
46
43
  "express": "^4.17.1",
47
44
  "mockjs": "^1.1.0",
48
- "multer": "^1.4.5-lts.1"
45
+ "multer": "^1.4.5-lts.1",
46
+ "open": "^8.4.0",
47
+ "uuid": "^9.0.0",
48
+ "ws": "^8.2.3"
49
49
  },
50
50
  "devDependencies": {
51
+ "@types/commander": "^2.12.2",
51
52
  "@types/cors": "^2.8.13",
52
53
  "@types/express": "^4.17.13",
54
+ "@types/fs-extra": "^11.0.4",
53
55
  "@types/jest": "^27.5.2",
54
56
  "@types/mockjs": "^1.0.10",
55
57
  "@types/multer": "^1.4.12",
56
58
  "@types/node": "^16.18.0",
59
+ "@types/open": "^6.2.1",
60
+ "@types/supertest": "^6.0.2",
61
+ "@types/uuid": "^9.0.8",
62
+ "@types/ws": "^8.5.13",
63
+ "fs-extra": "^11.2.0",
57
64
  "jest": "^27.5.1",
58
65
  "nodemon": "^2.0.22",
66
+ "rimraf": "^3.0.2",
67
+ "supertest": "^7.0.0",
59
68
  "ts-jest": "^27.1.5",
60
69
  "ts-node": "^10.9.1",
61
70
  "typescript": "^4.9.5"