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/CONFIG.md CHANGED
@@ -302,41 +302,3 @@ You can configure file upload endpoints in your `data.json`:
302
302
  }
303
303
  }
304
304
  ```
305
-
306
- ### WebSocket Configuration
307
-
308
- | Field | Type | Required | Description |
309
- |-------|------|----------|-------------|
310
- | enabled | boolean | Yes | Enable/disable WebSocket support |
311
- | path | string | Yes | WebSocket endpoint path |
312
- | events | object | No | Event configurations |
313
-
314
- #### Event Configuration
315
-
316
- | Field | Type | Required | Description |
317
- |-------|------|----------|-------------|
318
- | mock.enabled | boolean | Yes | Enable/disable mock data for this event |
319
- | mock.interval | number | No | Interval (ms) for automatic data sending |
320
- | mock.template | object | Yes | Mock.js template for response data |
321
-
322
- Example:
323
- ```json
324
- {
325
- "websocket": {
326
- "enabled": true,
327
- "path": "/ws",
328
- "events": {
329
- "event-name": {
330
- "mock": {
331
- "enabled": true,
332
- "interval": 5000,
333
- "template": {
334
- "field1": "@value",
335
- "field2|1-100": 1
336
- }
337
- }
338
- }
339
- }
340
- }
341
- }
342
- ```
package/DESIGN.md ADDED
@@ -0,0 +1,227 @@
1
+ # JSON API Mocker 设计思路文档
2
+
3
+ ## 1. 项目架构设计
4
+
5
+ ### 1.1 核心模块划分
6
+ ```
7
+ src/
8
+ ├── types.ts # 类型定义
9
+ ├── server.ts # 服务器核心逻辑
10
+ ├── index.ts # 入口文件
11
+ └── cli.ts # 命令行工具
12
+ ```
13
+
14
+ ### 1.2 设计原则
15
+ - **配置驱动**: 通过 JSON 配置文件定义 API,而不是代码
16
+ - **约定优于配置**: 提供合理的默认值,减少配置复杂度
17
+ - **单一职责**: 每个模块只负责一个功能
18
+ - **开闭原则**: 扩展开放,修改关闭
19
+
20
+ ## 2. 关键技术决策
21
+
22
+ ### 2.1 为什么选择 JSON 配置文件
23
+ - **优点**:
24
+ - 零代码门槛
25
+ - 配置直观易读
26
+ - 方便版本控制
27
+ - 易于修改和共享
28
+ - **缺点**:
29
+ - 灵活性相对较低
30
+ - 不支持复杂逻辑
31
+
32
+ ### 2.2 为什么选择文件系统而不是数据库
33
+ - **优点**:
34
+ - 无需额外依赖
35
+ - 配置即数据,直观明了
36
+ - 方便迁移和备份
37
+ - **缺点**:
38
+ - 并发性能较差
39
+ - 不适合大规模数据
40
+
41
+ ### 2.3 为什么使用 TypeScript
42
+ - 类型安全
43
+ - 更好的开发体验
44
+ - 自动生成类型声明文件
45
+ - 便于维护和重构
46
+
47
+ ## 3. 核心功能实现
48
+
49
+ ### 3.1 路由系统设计
50
+ ```typescript
51
+ interface RouteConfig {
52
+ path: string;
53
+ methods: {
54
+ [key: string]: MethodConfig;
55
+ };
56
+ }
57
+
58
+ // 支持 RESTful API 的标准方法
59
+ type HttpMethod = 'get' | 'post' | 'put' | 'delete';
60
+ ```
61
+
62
+ ### 3.2 数据持久化方案
63
+ ```typescript
64
+ class MockServer {
65
+ private saveConfig() {
66
+ // 同步写入确保数据一致性
67
+ fs.writeFileSync(this.configPath, JSON.stringify(this.config, null, 2));
68
+ }
69
+ }
70
+ ```
71
+
72
+ ### 3.3 分页实现
73
+ ```typescript
74
+ interface PaginationConfig {
75
+ enabled: boolean;
76
+ pageSize: number;
77
+ totalCount: number;
78
+ }
79
+
80
+ // 分页处理逻辑
81
+ const handlePagination = (data: any[], page: number, pageSize: number) => {
82
+ const start = (page - 1) * pageSize;
83
+ return data.slice(start, start + pageSize);
84
+ };
85
+ ```
86
+
87
+ ## 4. 问题解决方案
88
+
89
+ ### 4.1 并发写入问题
90
+ - **问题**: 多个请求同时修改配置文件可能导致数据不一致
91
+ - **解决方案**:
92
+ 1. 使用同步写入
93
+ 2. 考虑添加文件锁
94
+ 3. 实现写入队列
95
+
96
+ ### 4.2 动态路由参数
97
+ - **问题**: 如何支持 `/users/:id` 这样的动态路径
98
+ - **解决方案**:
99
+ ```typescript
100
+ // 使用 Express 的路由参数功能
101
+ app.get(`${baseProxy}${path}/:id`, (req, res) => {
102
+ const id = req.params.id;
103
+ // 处理逻辑
104
+ });
105
+ ```
106
+
107
+ ### 4.3 类型安全
108
+ - **问题**: 如何确保运行时类型安全
109
+ - **解决方案**:
110
+ ```typescript
111
+ // 请求体验证
112
+ interface RequestSchema {
113
+ [key: string]: 'string' | 'number' | 'boolean';
114
+ }
115
+
116
+ const validateRequest = (body: any, schema: RequestSchema) => {
117
+ // 实现验证逻辑
118
+ };
119
+ ```
120
+
121
+ ## 5. 性能优化
122
+
123
+ ### 5.1 当前实现
124
+ - 同步文件操作
125
+ - 内存中保存配置副本
126
+ - 简单的错误处理
127
+
128
+ ### 5.2 可能的优化方向
129
+ 1. **缓存优化**
130
+ ```typescript
131
+ class Cache {
132
+ private static instance: Cache;
133
+ private store: Map<string, any>;
134
+
135
+ public get(key: string) {
136
+ return this.store.get(key);
137
+ }
138
+ }
139
+ ```
140
+
141
+ 2. **并发处理**
142
+ ```typescript
143
+ class WriteQueue {
144
+ private queue: Array<() => Promise<void>>;
145
+
146
+ public async add(task: () => Promise<void>) {
147
+ this.queue.push(task);
148
+ await this.process();
149
+ }
150
+ }
151
+ ```
152
+
153
+ ## 6. 扩展性设计
154
+
155
+ ### 6.1 中间件支持
156
+ ```typescript
157
+ interface ServerConfig {
158
+ middleware?: {
159
+ before?: Function[];
160
+ after?: Function[];
161
+ };
162
+ }
163
+ ```
164
+
165
+ ### 6.2 自定义响应处理
166
+ ```typescript
167
+ interface MethodConfig {
168
+ transform?: (data: any) => any;
169
+ headers?: Record<string, string>;
170
+ }
171
+ ```
172
+
173
+ ## 7. 未来规划
174
+
175
+ ### 7.1 短期目标
176
+ - ✅ 添加请求日志 (Completed in v1.2.0)
177
+ - ✅ 支持文件上传 (Completed in v1.2.5)
178
+ - ✅ 添加测试用例 (Completed in v1.2.6)
179
+
180
+ ### 7.2 长期目标
181
+ - ✅ 提供 Web 界面 (Completed in v2.0.0)
182
+ - 支持 WebSocket
183
+ - 支持数据库存储
184
+ - 支持集群部署
185
+
186
+ ## 8. 最佳实践
187
+
188
+ ### 8.1 配置文件组织
189
+ ```json
190
+ {
191
+ "server": {
192
+ "port": 8080,
193
+ "baseProxy": "/api"
194
+ },
195
+ "routes": [
196
+ {
197
+ "path": "/users",
198
+ "methods": {
199
+ "get": { ... },
200
+ "post": { ... }
201
+ }
202
+ }
203
+ ]
204
+ }
205
+ ```
206
+
207
+ ### 8.2 错误处理
208
+ ```typescript
209
+ class ApiError extends Error {
210
+ constructor(
211
+ public status: number,
212
+ message: string
213
+ ) {
214
+ super(message);
215
+ }
216
+ }
217
+
218
+ const errorHandler = (err: Error, req: Request, res: Response) => {
219
+ if (err instanceof ApiError) {
220
+ res.status(err.status).json({ error: err.message });
221
+ }
222
+ };
223
+ ```
224
+
225
+ ## 9. 总结
226
+
227
+ 本项目的核心是通过配置驱动的方式简化 Mock 服务器的搭建过程。虽然在性能和功能上有一些限制,但对于前端开发中的 Mock 需求来说是一个很好的解决方案。通过合理的模块划分和接口设计,我们既保证了代码的可维护性,也为未来的功能扩展留下了空间。