json-api-mocker 1.2.7 โ†’ 2.0.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/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,33 +10,55 @@ 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
18
+ - ๐Ÿ›  Customizable response structure
19
+ - ๐ŸŽญ Powerful data mocking with Mock.js
20
+ - ๐Ÿ“Š Real-time request logs and statistics
20
21
  - ๐Ÿ’ก TypeScript support
21
22
 
22
23
  ## ๐Ÿ“ฆ Installation
23
24
 
24
25
  ```bash
25
- # Using npm
26
- npm install json-api-mocker
26
+ npm install -g json-api-mocker
27
+ ```
28
+
29
+ ## ๐Ÿš€ Quick Start
27
30
 
28
- # Using yarn
29
- yarn add json-api-mocker
31
+ ### Method 1: Using Visual Interface (Recommended)
30
32
 
31
- # Using pnpm
32
- pnpm add json-api-mocker
33
+ 1. Create a `data.json` file:
34
+ ```json
35
+ {
36
+ "server": {
37
+ "port": 3000,
38
+ "baseProxy": "/api"
39
+ },
40
+ "routes": []
41
+ }
33
42
  ```
34
43
 
35
- ## ๐Ÿš€ Quick Start
44
+ 2. Start the server:
45
+ ```bash
46
+ # Start server and open browser
47
+ json-api-mocker -o
48
+
49
+ # Or specify port (default is 3000)
50
+ json-api-mocker -p 8080 -o
51
+ ```
36
52
 
37
- ### 1. Create Configuration File
53
+ After starting, the browser will automatically open the management interface, where you can:
54
+ 1. Visually create and manage APIs
55
+ 2. View real-time request logs
56
+ 3. Monitor API call statistics
57
+ 4. Debug mock data online
38
58
 
39
- Create a `data.json` file in your project root:
59
+ ### Method 2: Using Configuration File (Compatible with old version)
60
+
61
+ Create a `data.json` file:
40
62
 
41
63
  ```json
42
64
  {
@@ -46,40 +68,21 @@ Create a `data.json` file in your project root:
46
68
  },
47
69
  "routes": [
48
70
  {
49
- "path": "/users",
50
- "methods": {
51
- "get": {
52
- "type": "array",
53
- "pagination": {
54
- "enabled": true,
55
- "pageSize": 10,
56
- "totalCount": 100
57
- },
58
- "response": [
59
- {
60
- "id": 1,
61
- "name": "John",
62
- "age": 30,
63
- "city": "New York"
64
- }
65
- ]
66
- }
67
- }
68
- },
69
- {
70
- "path": "/upload/avatar",
71
- "methods": {
72
- "post": {
73
- "type": "object",
74
- "mock": {
75
- "enabled": true,
76
- "template": {
77
- "success": true,
78
- "message": "Upload successful",
71
+ "id": "user-api",
72
+ "route": {
73
+ "path": "/users",
74
+ "methods": {
75
+ "get": {
76
+ "status": 200,
77
+ "response": {
78
+ "code": 200,
79
+ "message": "success",
79
80
  "data": {
80
- "url": "@image('200x200')",
81
- "filename": "@string(10).jpg",
82
- "size": "@integer(1000, 1000000)"
81
+ "list|10": [{
82
+ "id": "@id",
83
+ "name": "@name",
84
+ "email": "@email"
85
+ }]
83
86
  }
84
87
  }
85
88
  }
@@ -90,110 +93,45 @@ Create a `data.json` file in your project root:
90
93
  }
91
94
  ```
92
95
 
93
- ### 2. Start the Server
94
-
95
- There are several ways to start the mock server:
96
+ Then start the server:
96
97
 
97
98
  ```bash
98
- # Method 1: Using npx (Recommended)
99
- npx json-api-mocker
100
-
101
- # Method 2: Using npx with a custom config file
102
- npx json-api-mocker ./custom-config.json
103
-
104
- # Method 3: If installed globally
105
99
  json-api-mocker
106
-
107
- # Method 4: If installed as a project dependency
108
- # Add this to your package.json scripts:
109
- {
110
- "scripts": {
111
- "mock": "json-api-mocker"
112
- }
113
- }
114
- # Then run:
115
- npm run mock
116
100
  ```
117
101
 
118
- Now your mock server is running at `http://localhost:8080`!
119
-
120
- You'll see output like this:
121
- ```bash
122
- Mock Server is running:
123
- - Address: http://localhost:8080
124
- - Base Path: /api
125
- Available APIs:
126
- GET http://localhost:8080/api/users
127
- POST http://localhost:8080/api/users
128
- POST http://localhost:8080/api/upload/avatar
129
- ```
130
-
131
- ## ๐Ÿ“– Configuration Guide
132
-
133
- For detailed configuration options, please refer to [CONFIG.md](./CONFIG.md).
102
+ ## ๐Ÿ“– Configuration
134
103
 
135
104
  ### Server Configuration
136
105
 
137
- The `server` section configures basic server settings:
138
-
139
106
  ```json
140
107
  {
141
108
  "server": {
142
- "port": 8080, // Server port number
143
- "baseProxy": "/api" // Base path for all routes
109
+ "port": 8080, // Server port
110
+ "baseProxy": "/api" // API base path
144
111
  }
145
112
  }
146
113
  ```
147
114
 
148
- ### Route Configuration
115
+ ### API Configuration
149
116
 
150
- Each route can support multiple HTTP methods:
117
+ Each API configuration includes:
151
118
 
152
119
  ```json
153
120
  {
154
- "path": "/users", // Route path
155
- "methods": {
156
- "get": {
157
- "type": "array", // Response type: "array" or "object"
158
- "pagination": { // Optional pagination settings
159
- "enabled": true,
160
- "pageSize": 10,
161
- "totalCount": 100
162
- },
163
- "response": [] // Response data
164
- },
165
- "post": {
166
- "requestSchema": { // Request body validation schema
167
- "name": "string",
168
- "age": "number"
169
- },
170
- "response": {
171
- "success": true
172
- }
173
- }
174
- }
175
- }
176
- ```
177
-
178
- ### File Upload Support
179
-
180
- You can configure file upload endpoints in your `data.json`:
181
-
182
- ```json
183
- {
184
- "path": "/upload/avatar",
185
- "methods": {
186
- "post": {
187
- "type": "object",
188
- "mock": {
189
- "enabled": true,
190
- "template": {
191
- "success": true,
192
- "message": "Upload successful",
121
+ "id": "unique-id", // API unique identifier
122
+ "route": {
123
+ "path": "/users", // API path (without base path)
124
+ "methods": { // Supported HTTP methods
125
+ "get": {
126
+ "status": 200, // Response status code
127
+ "headers": { // Custom response headers
128
+ "Content-Type": "application/json"
129
+ },
130
+ "response": { // Response data (supports Mock.js syntax)
131
+ "code": 200,
193
132
  "data": {
194
- "url": "@image('200x200')",
195
- "filename": "@string(10).jpg",
196
- "size": "@integer(1000, 1000000)"
133
+ "name": "@name",
134
+ "age": "@integer(18, 60)"
197
135
  }
198
136
  }
199
137
  }
@@ -202,113 +140,44 @@ You can configure file upload endpoints in your `data.json`:
202
140
  }
203
141
  ```
204
142
 
205
- #### Example Usage:
206
-
207
- ```bash
208
- # Upload single file
209
- curl -X POST http://localhost:8080/api/upload/avatar \
210
- -H "Content-Type: multipart/form-data" \
211
- -F "avatar=@/path/to/your/image.jpg"
212
-
213
- # Upload multiple files
214
- curl -X POST http://localhost:8080/api/upload/images \
215
- -H "Content-Type: multipart/form-data" \
216
- -F "images=@/path/to/image1.jpg" \
217
- -F "images=@/path/to/image2.jpg"
218
- ```
219
-
220
- For detailed configuration options, please refer to [CONFIG.md](./CONFIG.md#file-upload-configuration).
143
+ ## ๐ŸŽฎ Visual Interface Features
221
144
 
222
- ## ๐ŸŽฏ API Examples
145
+ ### 1. API Management
146
+ - Create, edit, and delete APIs
147
+ - Support multiple HTTP methods
148
+ - Visual response data editor
149
+ - Mock.js syntax hints
223
150
 
224
- ### Basic CRUD Operations
225
-
226
- #### Get Users List
227
- ```bash
228
- curl http://localhost:8080/api/users
229
- ```
230
-
231
- #### Get Single User
232
- ```bash
233
- curl http://localhost:8080/api/users/1
234
- ```
151
+ ### 2. Real-time Logs
152
+ - Request path and method
153
+ - Response status and duration
154
+ - Request parameters recording
155
+ - Response data viewing
235
156
 
236
- #### Create User
237
- ```bash
238
- curl -X POST http://localhost:8080/api/users \
239
- -H "Content-Type: application/json" \
240
- -d '{"name":"Alice","age":25,"city":"Boston"}'
241
- ```
157
+ ### 3. Statistics Dashboard
158
+ - Total API count
159
+ - Request volume monitoring
160
+ - Average response time
161
+ - Success rate statistics
242
162
 
243
- #### Update User
244
- ```bash
245
- curl -X PUT http://localhost:8080/api/users/1 \
246
- -H "Content-Type: application/json" \
247
- -d '{"name":"Alice","age":26,"city":"Boston"}'
248
- ```
163
+ ## ๐Ÿ”ง Command Line Options
249
164
 
250
- #### Delete User
251
165
  ```bash
252
- curl -X DELETE http://localhost:8080/api/users/1
253
- ```
254
-
255
- ### Advanced Usage
166
+ json-api-mocker [options]
256
167
 
257
- #### Pagination
258
- ```bash
259
- # Get page 2 with 10 items per page
260
- curl http://localhost:8080/api/users?page=2&pageSize=10
168
+ Options:
169
+ -p, --port <number> Specify server port (default: 8080)
170
+ -c, --config <path> Specify config file path (default: data.json)
171
+ -o, --open Auto open management interface
172
+ -h, --help Show help information
173
+ -v, --version Show version number
261
174
  ```
262
175
 
263
- #### Custom Response Headers
264
- The server automatically adds these headers:
265
- - `X-Total-Count`: Total number of items (for paginated responses)
266
-
267
- ## ๐Ÿ”ง Advanced Configuration
268
-
269
- ### Dynamic Routes
270
-
271
- You can use URL parameters in routes:
272
-
273
- ```json
274
- {
275
- "path": "/users/:id/posts",
276
- "methods": {
277
- "get": {
278
- "type": "array",
279
- "response": []
280
- }
281
- }
282
- }
283
- ```
284
-
285
- ### Request Validation
286
-
287
- Add schema validation for POST/PUT requests:
288
-
289
- ```json
290
- {
291
- "requestSchema": {
292
- "name": "string",
293
- "age": "number",
294
- "email": "string"
295
- }
296
- }
297
- ```
298
-
299
- ## ๐Ÿค Contributing
300
-
301
- 1. Fork the repository
302
- 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
303
- 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
304
- 4. Push to the branch (`git push origin feature/amazing-feature`)
305
- 5. Open a Pull Request
306
-
307
176
  ## ๐Ÿ“„ License
308
177
 
309
178
  MIT ยฉ [Xiong Haiyin]
310
179
 
311
180
  ## ๐Ÿ™ Acknowledgments
312
181
 
313
- - Express.js for the excellent web framework
314
- - All our contributors and users
182
+ - Thanks to all contributors and users
183
+ - 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,39 @@
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
+ commander_1.program
14
+ .version(require('../package.json').version)
15
+ .option('-c, --config <path>', '้…็ฝฎๆ–‡ไปถ่ทฏๅพ„', 'data.json')
16
+ .option('-p, --port <number>', 'ๆœๅŠกๅ™จ็ซฏๅฃ', '8080')
17
+ .option('-o, --open', '่‡ชๅŠจๆ‰“ๅผ€ๆต่งˆๅ™จ', false)
18
+ .parse(process.argv);
19
+ const options = commander_1.program.opts();
20
+ // ๅฏๅŠจ API Mock ๆœๅŠกๅ™จ
21
+ (0, index_1.startServer)(options.config);
22
+ // ๅˆ›ๅปบ้™ๆ€ๆ–‡ไปถๆœๅŠกๅ™จๆฅๆ‰˜็ฎกๅ‰็ซฏ้กต้ข
23
+ const app = (0, express_1.default)();
24
+ const httpServer = (0, http_1.createServer)(app);
25
+ // ไฝฟ็”จๆ‰“ๅŒ…ๅŽ็š„ๅ‰็ซฏๆ–‡ไปถ
26
+ app.use(express_1.default.static((0, path_1.join)(__dirname, '../web')));
27
+ // ๆ‰€ๆœ‰่ทฏ็”ฑ้ƒฝ่ฟ”ๅ›ž index.html
28
+ app.get('*', (req, res) => {
29
+ res.sendFile((0, path_1.join)(__dirname, '../web/index.html'));
30
+ });
31
+ // ๅฏๅŠจๅ‰็ซฏๆœๅŠกๅ™จ
32
+ const webPort = parseInt(options.port) + 1;
33
+ httpServer.listen(webPort, () => {
34
+ console.log(`Web UI is running on http://localhost:${webPort}`);
35
+ // ๅฆ‚ๆžœๆŒ‡ๅฎšไบ† --open ้€‰้กน๏ผŒ่‡ชๅŠจๆ‰“ๅผ€ๆต่งˆๅ™จ
36
+ if (options.open) {
37
+ (0, open_1.default)(`http://localhost:${webPort}`);
38
+ }
39
+ });
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export declare function startServer(configPath?: string): void;
2
- export { MockServer } from './server';
3
- 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,43 +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 = 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(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.server, 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);
package/dist/server.d.ts CHANGED
@@ -1,18 +1,21 @@
1
- import { Express } from 'express';
2
- import { Config } from './types';
3
- export declare class MockServer {
4
- private app;
5
- private config;
6
- private configPath;
7
- constructor(config: Config, configPath?: string);
8
- getApp(): Express;
9
- private setupMiddleware;
10
- private logRequest;
11
- private generateMockData;
12
- private handleRequest;
13
- private setupRoutes;
14
- private createRoute;
15
- private findRouteConfig;
16
- private generateMockResponse;
17
- start(): void;
18
- }
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
+ }