json-api-mocker 3.0.0 → 3.1.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 with JSON configuration and visual management interface.
3
+ A lightweight and flexible mock server that uses JSON configuration to quickly create RESTful APIs.
4
4
 
5
5
  <p align="center">
6
6
  <img src="https://img.shields.io/npm/v/json-api-mocker" alt="npm version" />
@@ -10,57 +10,35 @@ A lightweight and flexible mock server with JSON configuration and visual manage
10
10
 
11
11
  ## ✨ Features
12
12
 
13
- - 🚀 Brand new visual management interface
14
- - 🚀 Support both configuration file and UI management
15
- - 🔄 Support all common HTTP methods
13
+ - 🚀 Quick setup with JSON configuration
14
+ - 🔄 Support for GET, POST, PUT, DELETE methods
15
+ - 🖥️ Visual admin console, no JSON editing required
16
16
  - 📝 Automatic data persistence
17
17
  - 🔍 Built-in pagination support
18
- - 🛠 Customizable response structure
19
- - 🎭 Powerful data mocking with Mock.js
20
- - 📊 Real-time request logs and statistics
18
+ - 🛠 Customizable response schemas
19
+ - 🎭 Integration with Mock.js for powerful data mocking
20
+ - 📤 File upload support
21
+ - 🔌 Real-time communication with WebSocket
21
22
  - 💡 TypeScript support
22
23
 
23
24
  ## 📦 Installation
24
25
 
25
26
  ```bash
26
- npm install -g json-api-mocker
27
- ```
28
-
29
- ## 🚀 Quick Start
30
-
31
- The server uses fixed ports:
32
- - API Server: 35728
33
- - Web UI: 35729
34
- - WebSocket: 35730
27
+ # Using npm
28
+ npm install json-api-mocker
35
29
 
36
- ### Method 1: Using Visual Interface (Recommended)
30
+ # Using yarn
31
+ yarn add json-api-mocker
37
32
 
38
- 1. Create a `data.json` file:
39
- ```json
40
- {
41
- "server": {
42
- "port": 35728,
43
- "baseProxy": "/api"
44
- },
45
- "routes": []
46
- }
47
- ```
48
-
49
- 2. Start the server:
50
- ```bash
51
- # Start server and open browser
52
- json-api-mocker -o
33
+ # Using pnpm
34
+ pnpm add json-api-mocker
53
35
  ```
54
36
 
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
+ ## 🚀 Quick Start
60
38
 
61
- ### Method 2: Using Configuration File (Compatible with old version)
39
+ ### 1. Create Configuration File
62
40
 
63
- Create a `data.json` file:
41
+ Create a `data.json` file in your project root:
64
42
 
65
43
  ```json
66
44
  {
@@ -70,21 +48,40 @@ Create a `data.json` file:
70
48
  },
71
49
  "routes": [
72
50
  {
73
- "id": "user-api",
74
- "route": {
75
- "path": "/users",
76
- "methods": {
77
- "get": {
78
- "status": 200,
79
- "response": {
80
- "code": 200,
81
- "message": "success",
51
+ "path": "/users",
52
+ "methods": {
53
+ "get": {
54
+ "type": "array",
55
+ "pagination": {
56
+ "enabled": true,
57
+ "pageSize": 10,
58
+ "totalCount": 100
59
+ },
60
+ "response": [
61
+ {
62
+ "id": 1,
63
+ "name": "John",
64
+ "age": 30,
65
+ "city": "New York"
66
+ }
67
+ ]
68
+ }
69
+ }
70
+ },
71
+ {
72
+ "path": "/upload/avatar",
73
+ "methods": {
74
+ "post": {
75
+ "type": "object",
76
+ "mock": {
77
+ "enabled": true,
78
+ "template": {
79
+ "success": true,
80
+ "message": "Upload successful",
82
81
  "data": {
83
- "list|10": [{
84
- "id": "@id",
85
- "name": "@name",
86
- "email": "@email"
87
- }]
82
+ "url": "@image('200x200')",
83
+ "filename": "@string(10).jpg",
84
+ "size": "@integer(1000, 1000000)"
88
85
  }
89
86
  }
90
87
  }
@@ -95,45 +92,129 @@ Create a `data.json` file:
95
92
  }
96
93
  ```
97
94
 
98
- Then start the server:
95
+ ### 2. Start the Server
96
+
97
+ There are several ways to start the mock server:
99
98
 
100
99
  ```bash
100
+ # Method 1: Using npx (Recommended)
101
+ npx json-api-mocker
102
+
103
+ # Method 2: Using npx with a custom config file
104
+ npx json-api-mocker ./custom-config.json
105
+
106
+ # Method 3: If installed globally
101
107
  json-api-mocker
108
+
109
+ # Method 4: If installed as a project dependency
110
+ # Add this to your package.json scripts:
111
+ {
112
+ "scripts": {
113
+ "mock": "json-api-mocker"
114
+ }
115
+ }
116
+ # Then run:
117
+ npm run mock
118
+ ```
119
+
120
+ Now your mock server is running at `http://localhost:8080`!
121
+
122
+ You'll see output like this:
123
+ ```bash
124
+ Mock 服务器已启动:
125
+ - HTTP 地址: http://localhost:8080
126
+ - 管理后台: http://localhost:8080/admin
127
+ - 基础路径: /api
128
+ 可用的接口:
129
+ GET http://localhost:8080/api/users
130
+ POST http://localhost:8080/api/users
131
+ POST http://localhost:8080/api/upload/avatar
102
132
  ```
103
133
 
104
- ## 📖 Configuration
134
+ ## 🖥️ Visual Admin Console
135
+
136
+ Don't want to write JSON config by hand? After starting the server, open the admin console in your browser:
137
+
138
+ ```
139
+ http://localhost:8080/admin
140
+ ```
141
+
142
+ The admin console provides the following features:
143
+
144
+ - 📝 **Visual Editor**: Configure routes, methods, and Mock fields via forms — no JSON knowledge required
145
+ - 🎨 **Field Builder**: Select field types (random name, age range, email, city, etc.) from a dropdown to auto-generate Mock.js templates
146
+ - 💻 **JSON Source Editor**: Switch to source mode to edit JSON directly, with formatting and syntax checking
147
+ - 👀 **API Preview**: View all available APIs; GET endpoints can be tested with one click
148
+ - 💾 **One-click Save**: Save changes and they're automatically written back to `data.json`
149
+
150
+ > 💡 After saving, static data changes take effect immediately; newly added routes require a server restart.
151
+
152
+ ## 📖 Configuration Guide
153
+
154
+ For detailed configuration options, please refer to [CONFIG.md](./CONFIG.md).
105
155
 
106
156
  ### Server Configuration
107
157
 
158
+ The `server` section configures basic server settings:
159
+
108
160
  ```json
109
161
  {
110
162
  "server": {
111
- "port": 8080, // Server port
112
- "baseProxy": "/api" // API base path
163
+ "port": 8080, // Server port number
164
+ "baseProxy": "/api" // Base path for all routes
113
165
  }
114
166
  }
115
167
  ```
116
168
 
117
- ### API Configuration
169
+ ### Route Configuration
118
170
 
119
- Each API configuration includes:
171
+ Each route can support multiple HTTP methods:
120
172
 
121
173
  ```json
122
174
  {
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,
175
+ "path": "/users", // Route path
176
+ "methods": {
177
+ "get": {
178
+ "type": "array", // Response type: "array" or "object"
179
+ "pagination": { // Optional pagination settings
180
+ "enabled": true,
181
+ "pageSize": 10,
182
+ "totalCount": 100
183
+ },
184
+ "response": [] // Response data
185
+ },
186
+ "post": {
187
+ "requestSchema": { // Request body validation schema
188
+ "name": "string",
189
+ "age": "number"
190
+ },
191
+ "response": {
192
+ "success": true
193
+ }
194
+ }
195
+ }
196
+ }
197
+ ```
198
+
199
+ ### File Upload Support
200
+
201
+ You can configure file upload endpoints in your `data.json`:
202
+
203
+ ```json
204
+ {
205
+ "path": "/upload/avatar",
206
+ "methods": {
207
+ "post": {
208
+ "type": "object",
209
+ "mock": {
210
+ "enabled": true,
211
+ "template": {
212
+ "success": true,
213
+ "message": "Upload successful",
134
214
  "data": {
135
- "name": "@name",
136
- "age": "@integer(18, 60)"
215
+ "url": "@image('200x200')",
216
+ "filename": "@string(10).jpg",
217
+ "size": "@integer(1000, 1000000)"
137
218
  }
138
219
  }
139
220
  }
@@ -142,44 +223,196 @@ Each API configuration includes:
142
223
  }
143
224
  ```
144
225
 
145
- ## 🎮 Visual Interface Features
226
+ #### Example Usage:
227
+
228
+ ```bash
229
+ # Upload single file
230
+ curl -X POST http://localhost:8080/api/upload/avatar \
231
+ -H "Content-Type: multipart/form-data" \
232
+ -F "avatar=@/path/to/your/image.jpg"
233
+
234
+ # Upload multiple files
235
+ curl -X POST http://localhost:8080/api/upload/images \
236
+ -H "Content-Type: multipart/form-data" \
237
+ -F "images=@/path/to/image1.jpg" \
238
+ -F "images=@/path/to/image2.jpg"
239
+ ```
240
+
241
+ For detailed configuration options, please refer to [CONFIG.md](./CONFIG.md#file-upload-configuration).
242
+
243
+ ## 🎯 API Examples
146
244
 
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
245
+ ### Basic CRUD Operations
152
246
 
153
- ### 2. Real-time Logs
154
- - Request path and method
155
- - Response status and duration
156
- - Request parameters recording
157
- - Response data viewing
247
+ #### Get Users List
248
+ ```bash
249
+ curl http://localhost:8080/api/users
250
+ ```
251
+
252
+ #### Get Single User
253
+ ```bash
254
+ curl http://localhost:8080/api/users/1
255
+ ```
256
+
257
+ #### Create User
258
+ ```bash
259
+ curl -X POST http://localhost:8080/api/users \
260
+ -H "Content-Type: application/json" \
261
+ -d '{"name":"Alice","age":25,"city":"Boston"}'
262
+ ```
263
+
264
+ #### Update User
265
+ ```bash
266
+ curl -X PUT http://localhost:8080/api/users/1 \
267
+ -H "Content-Type: application/json" \
268
+ -d '{"name":"Alice","age":26,"city":"Boston"}'
269
+ ```
158
270
 
159
- ### 3. Statistics Dashboard
160
- - Total API count
161
- - Request volume monitoring
162
- - Average response time
163
- - Success rate statistics
271
+ #### Delete User
272
+ ```bash
273
+ curl -X DELETE http://localhost:8080/api/users/1
274
+ ```
164
275
 
165
- ## 🔧 Command Line Options
276
+ ### Advanced Usage
166
277
 
278
+ #### Pagination
167
279
  ```bash
168
- json-api-mocker [options]
280
+ # Get page 2 with 10 items per page
281
+ curl http://localhost:8080/api/users?page=2&pageSize=10
282
+ ```
283
+
284
+ #### Custom Response Headers
285
+ The server automatically adds these headers:
286
+ - `X-Total-Count`: Total number of items (for paginated responses)
287
+
288
+ ## 🔧 Advanced Configuration
289
+
290
+ ### Dynamic Routes
291
+
292
+ You can use URL parameters in routes:
293
+
294
+ ```json
295
+ {
296
+ "path": "/users/:id/posts",
297
+ "methods": {
298
+ "get": {
299
+ "type": "array",
300
+ "response": []
301
+ }
302
+ }
303
+ }
304
+ ```
305
+
306
+ ### Request Validation
307
+
308
+ Add schema validation for POST/PUT requests:
309
+
310
+ ```json
311
+ {
312
+ "requestSchema": {
313
+ "name": "string",
314
+ "age": "number",
315
+ "email": "string"
316
+ }
317
+ }
318
+ ```
319
+
320
+ ### WebSocket Support
321
+
322
+ You can configure WebSocket endpoints in your `data.json`:
323
+
324
+ ```json
325
+ {
326
+ "websocket": {
327
+ "enabled": true,
328
+ "path": "/ws",
329
+ "events": {
330
+ "realtime-data": {
331
+ "mock": {
332
+ "enabled": true,
333
+ "interval": 5000, // Send data every 5 seconds
334
+ "template": {
335
+ "timestamp": "@datetime",
336
+ "value|1-100": 1,
337
+ "status|1": ["normal", "warning", "error"]
338
+ }
339
+ }
340
+ },
341
+ "user-status": {
342
+ "mock": {
343
+ "enabled": true,
344
+ "template": {
345
+ "userId|+1": 1,
346
+ "status|1": ["online", "offline", "away"],
347
+ "lastActive": "@datetime"
348
+ }
349
+ }
350
+ }
351
+ }
352
+ }
353
+ }
354
+ ```
169
355
 
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
356
+ #### Client Usage Example:
357
+
358
+ ```javascript
359
+ // Connect to WebSocket server
360
+ const ws = new WebSocket('ws://localhost:8080/ws');
361
+
362
+ // Handle connection open
363
+ ws.onopen = () => {
364
+ console.log('Connected to WebSocket server');
365
+
366
+ // Request real-time data
367
+ ws.send(JSON.stringify({
368
+ event: 'realtime-data'
369
+ }));
370
+ };
371
+
372
+ // Handle incoming messages
373
+ ws.onmessage = (event) => {
374
+ const data = JSON.parse(event.data);
375
+ console.log('Received:', data);
376
+ // {
377
+ // event: 'realtime-data',
378
+ // data: {
379
+ // timestamp: '2024-01-01 12:00:00',
380
+ // value: 75,
381
+ // status: 'normal'
382
+ // }
383
+ // }
384
+ };
385
+
386
+ // Handle errors
387
+ ws.onerror = (error) => {
388
+ console.error('WebSocket error:', error);
389
+ };
390
+
391
+ // Handle connection close
392
+ ws.onclose = () => {
393
+ console.log('Disconnected from WebSocket server');
394
+ };
176
395
  ```
177
396
 
397
+ #### Features:
398
+ - Event-based communication
399
+ - Automatic data sending at specified intervals
400
+ - Mock.js template support for dynamic data
401
+ - Multiple event handlers
402
+
403
+ ## 🤝 Contributing
404
+
405
+ 1. Fork the repository
406
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
407
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
408
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
409
+ 5. Open a Pull Request
410
+
178
411
  ## 📄 License
179
412
 
180
413
  MIT © [Xiong Haiyin]
181
414
 
182
415
  ## 🙏 Acknowledgments
183
416
 
184
- - Thanks to all contributors and users
185
- - Special thanks to Mock.js for data mocking support
417
+ - Express.js for the excellent web framework
418
+ - All our contributors and users
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,41 +1,6 @@
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
- });
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);
package/dist/index.d.ts CHANGED
@@ -1,7 +1,3 @@
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';
1
+ export declare function startServer(configPath?: string): void;
2
+ export { MockServer } from './server';
3
+ export * from './types';
package/dist/index.js CHANGED
@@ -1,48 +1,43 @@
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);
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(configPath = 'data.json') {
25
+ const fullPath = path_1.default.resolve(process.cwd(), configPath);
26
+ try {
27
+ const configContent = fs_1.default.readFileSync(fullPath, 'utf-8');
28
+ const config = JSON.parse(configContent);
29
+ const server = new server_1.MockServer(config, configPath);
30
+ server.start();
31
+ }
32
+ catch (error) {
33
+ console.error('Failed to start server:', error);
34
+ process.exit(1);
35
+ }
36
+ }
37
+ exports.startServer = startServer;
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);