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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # JSON API Mocker
2
2
 
3
- A lightweight and flexible mock server that uses JSON configuration to quickly create RESTful APIs.
3
+ A lightweight and flexible mock server with JSON configuration and visual management interface.
4
4
 
5
5
  <p align="center">
6
6
  <img src="https://img.shields.io/npm/v/json-api-mocker" alt="npm version" />
@@ -10,34 +10,57 @@ A lightweight and flexible mock server that uses JSON configuration to quickly c
10
10
 
11
11
  ## ✨ Features
12
12
 
13
- - 🚀 Quick setup with JSON configuration
14
- - 🔄 Support for GET, POST, PUT, DELETE methods
13
+ - 🚀 Brand new visual management interface
14
+ - 🚀 Support both configuration file and UI management
15
+ - 🔄 Support all common HTTP methods
15
16
  - 📝 Automatic data persistence
16
17
  - 🔍 Built-in pagination support
17
- - 🛠 Customizable response schemas
18
- - 🎭 Integration with Mock.js for powerful data mocking
19
- - 📤 File upload support
20
- - 🔌 Real-time communication with WebSocket
18
+ - 🛠 Customizable response structure
19
+ - 🎭 Powerful data mocking with Mock.js
20
+ - 📊 Real-time request logs and statistics
21
21
  - 💡 TypeScript support
22
22
 
23
23
  ## 📦 Installation
24
24
 
25
25
  ```bash
26
- # Using npm
27
- npm install json-api-mocker
26
+ npm install -g json-api-mocker
27
+ ```
28
+
29
+ ## 🚀 Quick Start
28
30
 
29
- # Using yarn
30
- yarn add json-api-mocker
31
+ The server uses fixed ports:
32
+ - API Server: 35728
33
+ - Web UI: 35729
34
+ - WebSocket: 35730
31
35
 
32
- # Using pnpm
33
- pnpm add json-api-mocker
36
+ ### Method 1: Using Visual Interface (Recommended)
37
+
38
+ 1. Create a `data.json` file:
39
+ ```json
40
+ {
41
+ "server": {
42
+ "port": 35728,
43
+ "baseProxy": "/api"
44
+ },
45
+ "routes": []
46
+ }
34
47
  ```
35
48
 
36
- ## 🚀 Quick Start
49
+ 2. Start the server:
50
+ ```bash
51
+ # Start server and open browser
52
+ json-api-mocker -o
53
+ ```
54
+
55
+ After starting, the browser will automatically open the management interface, where you can:
56
+ 1. Visually create and manage APIs
57
+ 2. View real-time request logs
58
+ 3. Monitor API call statistics
59
+ 4. Debug mock data online
37
60
 
38
- ### 1. Create Configuration File
61
+ ### Method 2: Using Configuration File (Compatible with old version)
39
62
 
40
- Create a `data.json` file in your project root:
63
+ Create a `data.json` file:
41
64
 
42
65
  ```json
43
66
  {
@@ -47,40 +70,21 @@ Create a `data.json` file in your project root:
47
70
  },
48
71
  "routes": [
49
72
  {
50
- "path": "/users",
51
- "methods": {
52
- "get": {
53
- "type": "array",
54
- "pagination": {
55
- "enabled": true,
56
- "pageSize": 10,
57
- "totalCount": 100
58
- },
59
- "response": [
60
- {
61
- "id": 1,
62
- "name": "John",
63
- "age": 30,
64
- "city": "New York"
65
- }
66
- ]
67
- }
68
- }
69
- },
70
- {
71
- "path": "/upload/avatar",
72
- "methods": {
73
- "post": {
74
- "type": "object",
75
- "mock": {
76
- "enabled": true,
77
- "template": {
78
- "success": true,
79
- "message": "Upload successful",
73
+ "id": "user-api",
74
+ "route": {
75
+ "path": "/users",
76
+ "methods": {
77
+ "get": {
78
+ "status": 200,
79
+ "response": {
80
+ "code": 200,
81
+ "message": "success",
80
82
  "data": {
81
- "url": "@image('200x200')",
82
- "filename": "@string(10).jpg",
83
- "size": "@integer(1000, 1000000)"
83
+ "list|10": [{
84
+ "id": "@id",
85
+ "name": "@name",
86
+ "email": "@email"
87
+ }]
84
88
  }
85
89
  }
86
90
  }
@@ -91,110 +95,45 @@ Create a `data.json` file in your project root:
91
95
  }
92
96
  ```
93
97
 
94
- ### 2. Start the Server
95
-
96
- There are several ways to start the mock server:
98
+ Then start the server:
97
99
 
98
100
  ```bash
99
- # Method 1: Using npx (Recommended)
100
- npx json-api-mocker
101
-
102
- # Method 2: Using npx with a custom config file
103
- npx json-api-mocker ./custom-config.json
104
-
105
- # Method 3: If installed globally
106
101
  json-api-mocker
107
-
108
- # Method 4: If installed as a project dependency
109
- # Add this to your package.json scripts:
110
- {
111
- "scripts": {
112
- "mock": "json-api-mocker"
113
- }
114
- }
115
- # Then run:
116
- npm run mock
117
- ```
118
-
119
- Now your mock server is running at `http://localhost:8080`!
120
-
121
- You'll see output like this:
122
- ```bash
123
- Mock Server is running:
124
- - Address: http://localhost:8080
125
- - Base Path: /api
126
- Available APIs:
127
- GET http://localhost:8080/api/users
128
- POST http://localhost:8080/api/users
129
- POST http://localhost:8080/api/upload/avatar
130
102
  ```
131
103
 
132
- ## 📖 Configuration Guide
133
-
134
- For detailed configuration options, please refer to [CONFIG.md](./CONFIG.md).
104
+ ## 📖 Configuration
135
105
 
136
106
  ### Server Configuration
137
107
 
138
- The `server` section configures basic server settings:
139
-
140
108
  ```json
141
109
  {
142
110
  "server": {
143
- "port": 8080, // Server port number
144
- "baseProxy": "/api" // Base path for all routes
145
- }
146
- }
147
- ```
148
-
149
- ### Route Configuration
150
-
151
- Each route can support multiple HTTP methods:
152
-
153
- ```json
154
- {
155
- "path": "/users", // Route path
156
- "methods": {
157
- "get": {
158
- "type": "array", // Response type: "array" or "object"
159
- "pagination": { // Optional pagination settings
160
- "enabled": true,
161
- "pageSize": 10,
162
- "totalCount": 100
163
- },
164
- "response": [] // Response data
165
- },
166
- "post": {
167
- "requestSchema": { // Request body validation schema
168
- "name": "string",
169
- "age": "number"
170
- },
171
- "response": {
172
- "success": true
173
- }
174
- }
111
+ "port": 8080, // Server port
112
+ "baseProxy": "/api" // API base path
175
113
  }
176
114
  }
177
115
  ```
178
116
 
179
- ### File Upload Support
117
+ ### API Configuration
180
118
 
181
- You can configure file upload endpoints in your `data.json`:
119
+ Each API configuration includes:
182
120
 
183
121
  ```json
184
122
  {
185
- "path": "/upload/avatar",
186
- "methods": {
187
- "post": {
188
- "type": "object",
189
- "mock": {
190
- "enabled": true,
191
- "template": {
192
- "success": true,
193
- "message": "Upload successful",
123
+ "id": "unique-id", // API unique identifier
124
+ "route": {
125
+ "path": "/users", // API path (without base path)
126
+ "methods": { // Supported HTTP methods
127
+ "get": {
128
+ "status": 200, // Response status code
129
+ "headers": { // Custom response headers
130
+ "Content-Type": "application/json"
131
+ },
132
+ "response": { // Response data (supports Mock.js syntax)
133
+ "code": 200,
194
134
  "data": {
195
- "url": "@image('200x200')",
196
- "filename": "@string(10).jpg",
197
- "size": "@integer(1000, 1000000)"
135
+ "name": "@name",
136
+ "age": "@integer(18, 60)"
198
137
  }
199
138
  }
200
139
  }
@@ -203,196 +142,44 @@ You can configure file upload endpoints in your `data.json`:
203
142
  }
204
143
  ```
205
144
 
206
- #### Example Usage:
207
-
208
- ```bash
209
- # Upload single file
210
- curl -X POST http://localhost:8080/api/upload/avatar \
211
- -H "Content-Type: multipart/form-data" \
212
- -F "avatar=@/path/to/your/image.jpg"
213
-
214
- # Upload multiple files
215
- curl -X POST http://localhost:8080/api/upload/images \
216
- -H "Content-Type: multipart/form-data" \
217
- -F "images=@/path/to/image1.jpg" \
218
- -F "images=@/path/to/image2.jpg"
219
- ```
220
-
221
- For detailed configuration options, please refer to [CONFIG.md](./CONFIG.md#file-upload-configuration).
222
-
223
- ## 🎯 API Examples
224
-
225
- ### Basic CRUD Operations
226
-
227
- #### Get Users List
228
- ```bash
229
- curl http://localhost:8080/api/users
230
- ```
231
-
232
- #### Get Single User
233
- ```bash
234
- curl http://localhost:8080/api/users/1
235
- ```
145
+ ## 🎮 Visual Interface Features
236
146
 
237
- #### Create User
238
- ```bash
239
- curl -X POST http://localhost:8080/api/users \
240
- -H "Content-Type: application/json" \
241
- -d '{"name":"Alice","age":25,"city":"Boston"}'
242
- ```
147
+ ### 1. API Management
148
+ - Create, edit, and delete APIs
149
+ - Support multiple HTTP methods
150
+ - Visual response data editor
151
+ - Mock.js syntax hints
243
152
 
244
- #### Update User
245
- ```bash
246
- curl -X PUT http://localhost:8080/api/users/1 \
247
- -H "Content-Type: application/json" \
248
- -d '{"name":"Alice","age":26,"city":"Boston"}'
249
- ```
153
+ ### 2. Real-time Logs
154
+ - Request path and method
155
+ - Response status and duration
156
+ - Request parameters recording
157
+ - Response data viewing
250
158
 
251
- #### Delete User
252
- ```bash
253
- curl -X DELETE http://localhost:8080/api/users/1
254
- ```
159
+ ### 3. Statistics Dashboard
160
+ - Total API count
161
+ - Request volume monitoring
162
+ - Average response time
163
+ - Success rate statistics
255
164
 
256
- ### Advanced Usage
165
+ ## 🔧 Command Line Options
257
166
 
258
- #### Pagination
259
167
  ```bash
260
- # Get page 2 with 10 items per page
261
- curl http://localhost:8080/api/users?page=2&pageSize=10
262
- ```
263
-
264
- #### Custom Response Headers
265
- The server automatically adds these headers:
266
- - `X-Total-Count`: Total number of items (for paginated responses)
267
-
268
- ## 🔧 Advanced Configuration
269
-
270
- ### Dynamic Routes
271
-
272
- You can use URL parameters in routes:
273
-
274
- ```json
275
- {
276
- "path": "/users/:id/posts",
277
- "methods": {
278
- "get": {
279
- "type": "array",
280
- "response": []
281
- }
282
- }
283
- }
284
- ```
285
-
286
- ### Request Validation
168
+ json-api-mocker [options]
287
169
 
288
- Add schema validation for POST/PUT requests:
289
-
290
- ```json
291
- {
292
- "requestSchema": {
293
- "name": "string",
294
- "age": "number",
295
- "email": "string"
296
- }
297
- }
298
- ```
299
-
300
- ### WebSocket Support
301
-
302
- You can configure WebSocket endpoints in your `data.json`:
303
-
304
- ```json
305
- {
306
- "websocket": {
307
- "enabled": true,
308
- "path": "/ws",
309
- "events": {
310
- "realtime-data": {
311
- "mock": {
312
- "enabled": true,
313
- "interval": 5000, // Send data every 5 seconds
314
- "template": {
315
- "timestamp": "@datetime",
316
- "value|1-100": 1,
317
- "status|1": ["normal", "warning", "error"]
318
- }
319
- }
320
- },
321
- "user-status": {
322
- "mock": {
323
- "enabled": true,
324
- "template": {
325
- "userId|+1": 1,
326
- "status|1": ["online", "offline", "away"],
327
- "lastActive": "@datetime"
328
- }
329
- }
330
- }
331
- }
332
- }
333
- }
334
- ```
335
-
336
- #### Client Usage Example:
337
-
338
- ```javascript
339
- // Connect to WebSocket server
340
- const ws = new WebSocket('ws://localhost:8080/ws');
341
-
342
- // Handle connection open
343
- ws.onopen = () => {
344
- console.log('Connected to WebSocket server');
345
-
346
- // Request real-time data
347
- ws.send(JSON.stringify({
348
- event: 'realtime-data'
349
- }));
350
- };
351
-
352
- // Handle incoming messages
353
- ws.onmessage = (event) => {
354
- const data = JSON.parse(event.data);
355
- console.log('Received:', data);
356
- // {
357
- // event: 'realtime-data',
358
- // data: {
359
- // timestamp: '2024-01-01 12:00:00',
360
- // value: 75,
361
- // status: 'normal'
362
- // }
363
- // }
364
- };
365
-
366
- // Handle errors
367
- ws.onerror = (error) => {
368
- console.error('WebSocket error:', error);
369
- };
370
-
371
- // Handle connection close
372
- ws.onclose = () => {
373
- console.log('Disconnected from WebSocket server');
374
- };
170
+ Options:
171
+ -p, --port <number> Specify server port (default: 8080)
172
+ -c, --config <path> Specify config file path (default: data.json)
173
+ -o, --open Auto open management interface
174
+ -h, --help Show help information
175
+ -v, --version Show version number
375
176
  ```
376
177
 
377
- #### Features:
378
- - Event-based communication
379
- - Automatic data sending at specified intervals
380
- - Mock.js template support for dynamic data
381
- - Multiple event handlers
382
-
383
- ## 🤝 Contributing
384
-
385
- 1. Fork the repository
386
- 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
387
- 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
388
- 4. Push to the branch (`git push origin feature/amazing-feature`)
389
- 5. Open a Pull Request
390
-
391
178
  ## 📄 License
392
179
 
393
180
  MIT © [Xiong Haiyin]
394
181
 
395
182
  ## 🙏 Acknowledgments
396
183
 
397
- - Express.js for the excellent web framework
398
- - All our contributors and users
184
+ - Thanks to all contributors and users
185
+ - Special thanks to Mock.js for data mocking support
package/dist/cli.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- #!/usr/bin/env node
2
- export {};
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js CHANGED
@@ -1,6 +1,41 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- const index_1 = require("./index");
5
- const configPath = process.argv[2] || 'data.json';
6
- (0, index_1.startServer)(configPath);
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const commander_1 = require("commander");
8
+ const index_1 = require("./index");
9
+ const path_1 = require("path");
10
+ const express_1 = __importDefault(require("express"));
11
+ const http_1 = require("http");
12
+ const open_1 = __importDefault(require("open"));
13
+ const WEB_PORT = 35729; // 前端页面端口
14
+ const WS_PORT = 35730; // WebSocket 端口
15
+ commander_1.program
16
+ .version(require('../package.json').version)
17
+ .option('-c, --config <path>', '配置文件路径', 'data.json')
18
+ .option('-o, --open', '自动打开浏览器', false)
19
+ .parse(process.argv);
20
+ const options = commander_1.program.opts();
21
+ // 启动 API Mock 服务器,不再传入端口参数,使用配置文件中的端口
22
+ (0, index_1.startServer)({
23
+ config: options.config,
24
+ wsPort: WS_PORT
25
+ });
26
+ // 创建静态文件服务器来托管前端页面
27
+ const app = (0, express_1.default)();
28
+ const httpServer = (0, http_1.createServer)(app);
29
+ // 使用打包后的前端文件
30
+ app.use(express_1.default.static((0, path_1.join)(__dirname, '../web')));
31
+ // 所有路由都返回 index.html
32
+ app.get('*', (req, res) => {
33
+ res.sendFile((0, path_1.join)(__dirname, '../web/index.html'));
34
+ });
35
+ // 启动前端服务器(使用固定端口)
36
+ httpServer.listen(WEB_PORT, () => {
37
+ console.log(`Web UI is running on http://localhost:${WEB_PORT}`);
38
+ if (options.open) {
39
+ (0, open_1.default)(`http://localhost:${WEB_PORT}`);
40
+ }
41
+ });
package/dist/index.d.ts CHANGED
@@ -1,3 +1,7 @@
1
- export declare function startServer(configPath?: string): void;
2
- export { MockServer } from './server';
3
- export * from './types';
1
+ interface StartOptions {
2
+ config?: string;
3
+ wsPort?: number;
4
+ }
5
+ export declare function startServer(options?: StartOptions): void;
6
+ export { MockServer } from './server';
7
+ export * from './types';
package/dist/index.js CHANGED
@@ -1,43 +1,48 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- var __importDefault = (this && this.__importDefault) || function (mod) {
17
- return (mod && mod.__esModule) ? mod : { "default": mod };
18
- };
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.MockServer = void 0;
21
- exports.startServer = startServer;
22
- const fs_1 = __importDefault(require("fs"));
23
- const path_1 = __importDefault(require("path"));
24
- const server_1 = require("./server");
25
- function startServer(configPath = 'data.json') {
26
- const fullPath = path_1.default.resolve(process.cwd(), configPath);
27
- try {
28
- const configContent = fs_1.default.readFileSync(fullPath, 'utf-8');
29
- const config = JSON.parse(configContent);
30
- const server = new server_1.MockServer(config, configPath);
31
- server.start();
32
- }
33
- catch (error) {
34
- console.error('Failed to start server:', error);
35
- process.exit(1);
36
- }
37
- }
38
- if (require.main === module) {
39
- startServer();
40
- }
41
- var server_2 = require("./server");
42
- Object.defineProperty(exports, "MockServer", { enumerable: true, get: function () { return server_2.MockServer; } });
43
- __exportStar(require("./types"), exports);
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.MockServer = exports.startServer = void 0;
21
+ const fs_1 = __importDefault(require("fs"));
22
+ const path_1 = __importDefault(require("path"));
23
+ const server_1 = require("./server");
24
+ function startServer(options = {}) {
25
+ const configPath = options.config || 'data.json';
26
+ const fullPath = path_1.default.resolve(process.cwd(), configPath);
27
+ try {
28
+ const configContent = fs_1.default.readFileSync(fullPath, 'utf-8');
29
+ const config = JSON.parse(configContent);
30
+ const serverConfig = {
31
+ ...config.server,
32
+ wsPort: options.wsPort
33
+ };
34
+ const server = new server_1.MockServer(serverConfig, configPath);
35
+ server.start();
36
+ }
37
+ catch (error) {
38
+ console.error('Failed to start server:', error);
39
+ process.exit(1);
40
+ }
41
+ }
42
+ exports.startServer = startServer;
43
+ if (require.main === module) {
44
+ startServer();
45
+ }
46
+ var server_2 = require("./server");
47
+ Object.defineProperty(exports, "MockServer", { enumerable: true, get: function () { return server_2.MockServer; } });
48
+ __exportStar(require("./types"), exports);