json-api-mocker 1.2.0 → 1.2.1
Sign up to get free protection for your applications and to get access to all the features.
- package/dist/server.d.ts +1 -0
- package/dist/server.js +21 -4
- package/package.json +1 -1
package/dist/server.d.ts
CHANGED
package/dist/server.js
CHANGED
@@ -10,6 +10,23 @@ const cors_1 = __importDefault(require("cors"));
|
|
10
10
|
class MockServer {
|
11
11
|
constructor(config, configPath = 'data.json') {
|
12
12
|
this.app = (0, express_1.default)();
|
13
|
+
this.logRequest = (req, res, next) => {
|
14
|
+
const startTime = Date.now();
|
15
|
+
const requestId = Math.random().toString(36).substring(7);
|
16
|
+
console.log(`[${new Date().toISOString()}] Request ${requestId}:`);
|
17
|
+
console.log(` Method: ${req.method}`);
|
18
|
+
console.log(` URL: ${req.url}`);
|
19
|
+
console.log(` Query Params: ${JSON.stringify(req.query)}`);
|
20
|
+
console.log(` Body: ${JSON.stringify(req.body)}`);
|
21
|
+
res.on('finish', () => {
|
22
|
+
const duration = Date.now() - startTime;
|
23
|
+
console.log(`[${new Date().toISOString()}] Response ${requestId}:`);
|
24
|
+
console.log(` Status: ${res.statusCode}`);
|
25
|
+
console.log(` Duration: ${duration}ms`);
|
26
|
+
console.log('----------------------------------------');
|
27
|
+
});
|
28
|
+
next();
|
29
|
+
};
|
13
30
|
this.config = config;
|
14
31
|
this.configPath = configPath;
|
15
32
|
this.setupMiddleware();
|
@@ -18,6 +35,7 @@ class MockServer {
|
|
18
35
|
setupMiddleware() {
|
19
36
|
this.app.use((0, cors_1.default)());
|
20
37
|
this.app.use(express_1.default.json());
|
38
|
+
this.app.use(this.logRequest);
|
21
39
|
}
|
22
40
|
generateMockData(config) {
|
23
41
|
try {
|
@@ -30,14 +48,13 @@ class MockServer {
|
|
30
48
|
return config.response;
|
31
49
|
}
|
32
50
|
catch (error) {
|
33
|
-
console.error('
|
51
|
+
console.error('Error generating mock data:', error);
|
34
52
|
return config.response;
|
35
53
|
}
|
36
54
|
}
|
37
55
|
handleRequest(config) {
|
38
56
|
return (req, res) => {
|
39
57
|
try {
|
40
|
-
console.log(`收到请求: ${req.method} ${req.url}`);
|
41
58
|
let responseData = this.generateMockData(config);
|
42
59
|
if (config.pagination?.enabled && Array.isArray(responseData)) {
|
43
60
|
const page = parseInt(req.query.page) || 1;
|
@@ -51,8 +68,8 @@ class MockServer {
|
|
51
68
|
res.json(responseData);
|
52
69
|
}
|
53
70
|
catch (error) {
|
54
|
-
console.error('
|
55
|
-
res.status(500).json({ error: '
|
71
|
+
console.error('Error handling request:', error);
|
72
|
+
res.status(500).json({ error: 'Internal server error' });
|
56
73
|
}
|
57
74
|
};
|
58
75
|
}
|