zenweb 6.4.0 → 6.5.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.
Files changed (4) hide show
  1. package/AGENTS.md +344 -201
  2. package/README.md +117 -82
  3. package/TEMPLATE.md +231 -0
  4. package/package.json +12 -11
package/AGENTS.md CHANGED
@@ -1,276 +1,419 @@
1
1
  # AGENTS.md
2
2
 
3
- AI 专用 API 参考文档,随 npm 包发布,供 AI 编程助手使用。
3
+ AI 专用 API 参考文档,供 AI 编程助手使用。
4
4
 
5
- ## 模块概述
5
+ **使用指引:**
6
+ - 创建新项目 → 阅读 `TEMPLATE.md`
7
+ - 理解现有代码 → 阅读 `AGENTS.md`
6
8
 
7
- ZenWeb 是基于 Koa 的模块化轻量级 Web 框架。`create()` 函数整合了多个常用模块,简化新项目配置,无需单独安装已集成模块。各模块详细用法请参阅其各自的 AGENTS.md 文件。
9
+ ---
8
10
 
9
- ## 导出
11
+ ## 概述
12
+
13
+ ZenWeb 是基于 Koa 的模块化轻量级 Web 框架。`create()` 整合多个模块,开箱即用。
14
+
15
+ **核心设计:**
16
+ - AsyncLocalStorage 全局 Helper,请求期间任意位置可用
17
+ - TypeScript 装饰器驱动的控制器和依赖注入
18
+ - 统一的成功/失败响应格式
19
+
20
+ ---
21
+
22
+ ## 快速启动
23
+
24
+ ```ts
25
+ import { create } from 'zenweb';
26
+
27
+ create({
28
+ controller: {
29
+ discoverPaths: ['./controller'],
30
+ autoControllerPrefix: true,
31
+ },
32
+ }).start();
33
+ ```
34
+
35
+ ---
36
+
37
+ ## TypeScript 配置(必需)
38
+
39
+ ```json
40
+ {
41
+ "compilerOptions": {
42
+ "experimentalDecorators": true,
43
+ "emitDecoratorMetadata": true,
44
+ "target": "ES2020",
45
+ "module": "commonjs"
46
+ }
47
+ }
48
+ ```
49
+
50
+ ---
51
+
52
+ ## 导出概览
10
53
 
11
54
  ```ts
12
55
  // 主函数
13
- export { create, Core, CreateOptions };
56
+ export { create, Core };
14
57
 
15
58
  // 依赖注入
16
- export { Init, Inject, Injectable, $getInstance } from '@zenweb/inject';
59
+ export { Injectable, Init, Inject, $getInstance } from '@zenweb/inject';
60
+
61
+ // 控制器装饰器
62
+ export { Controller, Get, Post, Put, Patch, Delete, All, Mapping } from '@zenweb/controller';
17
63
 
18
64
  // 路由
19
65
  export { Router, RouterMethod, RouterPath } from '@zenweb/router';
20
66
 
21
67
  // 结果处理
22
- export { ResultFail, fail } from '@zenweb/result';
68
+ export { fail, ResultFail } from '@zenweb/result';
23
69
 
24
- // 控制器装饰器
25
- export {
26
- Controller,
27
- Mapping,
28
- Get,
29
- Post,
30
- Put,
31
- Patch,
32
- Delete,
33
- All,
34
- } from '@zenweb/controller';
35
-
36
- // Core 相关
37
- export {
38
- Next,
39
- SetupFunction,
40
- Context,
41
- Middleware,
42
- SetupHelper,
43
- $getCore,
44
- $getContext,
45
- $core,
46
- $ctx,
47
- $debug,
48
- createDebug,
49
- } from '@zenweb/core';
50
-
51
- // Body 解析
52
- export {
53
- Body,
54
- ObjectBody,
55
- BodyHelper,
56
- RawBody,
57
- TextBody,
58
- useBodyParser,
59
- $body,
60
- $getTextBody,
61
- $getRawBody,
62
- $getObjectBody,
63
- } from '@zenweb/body';
64
-
65
- // Helper
66
- export {
67
- QueryHelper,
68
- TypeCastHelper,
69
- ParamHelper,
70
- $param,
71
- $query,
72
- $helperBase,
73
- } from '@zenweb/helper';
74
-
75
- // Log
76
- export {
77
- $log,
78
- $getLogger,
79
- Logger,
80
- } from '@zenweb/log';
70
+ // 全局 Helper($前缀,AsyncLocalStorage)
71
+ export { $ctx, $getCore, $getContext, $core, $debug, createDebug } from '@zenweb/core';
72
+ export { $body, $getObjectBody, $getRawBody, $getTextBody } from '@zenweb/body';
73
+ export { $param, $query, $helperBase } from '@zenweb/helper';
74
+ export { $log, $getLogger, Logger } from '@zenweb/log';
75
+
76
+ // Core 类型
77
+ export { Context, Middleware, Next, SetupFunction, SetupHelper } from '@zenweb/core';
81
78
  ```
82
79
 
83
- ## create(options?: CreateOptions)
80
+ ---
81
+
82
+ ## 控制器
84
83
 
85
- 创建应用实例,自动安装集成模块。
84
+ 控制器类自动标记为请求级注入,方法参数自动注入。
86
85
 
87
86
  ```ts
88
- import { create } from 'zenweb';
87
+ // controller/user.ts - 文件名映射为路由前缀 /user
88
+ export class UserController {
89
+ @Get() // GET /user
90
+ list() { return []; }
89
91
 
90
- create({
91
- // 全局实例,默认 true
92
- global: true,
93
-
94
- // 模块配置,设为 false 可禁用
95
- core: { env: 'production', keys: ['secret'] },
96
- meta: { showVersion: true, traceId: true },
97
- inject: false, // 禁用注入
98
- log: { dir: '/var/log/app' },
99
- router: false, // 禁用路由
100
- messagecode: { codes: { 'error': '错误' } },
101
- body: { limit: 1024 * 1024 },
102
- result: { failCode: 1, failStatus: 200 },
103
- helper: { page: { defaultLimit: 20 } },
104
- controller: { discoverPaths: ['./controller'], autoControllerPrefix: true },
105
- })
106
- .start();
92
+ @Get('/:id') // GET /user/:id
93
+ async detail(ctx: Context, service: UserService) {
94
+ const { id } = await $param.get({ id: '!int' });
95
+ return service.getById(id);
96
+ }
97
+
98
+ @Post() // POST /user
99
+ async create() {
100
+ return await $body.get({ name: '!string', email: 'string' });
101
+ }
102
+ }
107
103
  ```
108
104
 
109
- ## CreateOptions 类型
105
+ **@Controller 装饰器(可选):**
106
+ ```ts
107
+ @Controller({ prefix: '/admin' }) // 绝对前缀
108
+ @Controller({ prefix: 'manage' }) // 相对前缀,拼接自动前缀
109
+ @Controller({ middleware: [authFn] }) // 控制器级中间件
110
+ ```
111
+
112
+ **生命周期:**
113
+ ```ts
114
+ @Controller()
115
+ export class MyController {
116
+ constructor(private ctx: Context) {} // 自动注入
117
+
118
+ @Init
119
+ init() { /* 实例化后调用 */ }
120
+ }
121
+ ```
110
122
 
123
+ **单例控制器**(适用于无状态场景):
111
124
  ```ts
112
- interface CreateOptions {
113
- global?: boolean; // 全局实例,默认 true
114
- core?: CoreOption; // @zenweb/core 配置
115
- inject?: false; // 禁用 @zenweb/inject
116
- meta?: MetaOption | false; // @zenweb/meta 配置或禁用
117
- log?: LogOption | false; // @zenweb/log 配置或禁用
118
- router?: false; // 禁用 @zenweb/router
119
- messagecode?: MessageCodeOption | false;
120
- body?: BodyOption | false;
121
- result?: ResultOption | false;
122
- helper?: HelperOption | false;
123
- controller?: ControllerSetupOption | false;
125
+ @Controller()
126
+ @Injectable('singleton')
127
+ export class CounterController {
128
+ counter = 0;
129
+ @Get() index() { return ++this.counter; }
124
130
  }
125
131
  ```
126
132
 
127
- ## 集成模块列表
128
-
129
- 以下模块已集成,无需单独安装。详细 API 请参阅各模块 AGENTS.md:
130
-
131
- | 模块 | 作用 | 默认状态 |
132
- |------|------|----------|
133
- | `@zenweb/core` | 核心应用和上下文管理 | 启用 |
134
- | `@zenweb/meta` | 请求元信息(耗时、请求ID、追踪ID) | 启用 |
135
- | `@zenweb/inject` | 依赖注入系统 | 启用 |
136
- | `@zenweb/router` | Trie 高性能路由 | 启用 |
137
- | `@zenweb/log` | 请求日志 | 启用 |
138
- | `@zenweb/result` | 统一成功/失败响应处理 | 启用 |
139
- | `@zenweb/messagecode` | 错误消息代码格式化 | 启用 |
140
- | `@zenweb/controller` | 类控制器装饰器路由 | 启用 |
141
- | `@zenweb/helper` | 输入验证和类型转换助手 | 启用 |
142
- | `@zenweb/body` | 请求主体解析(JSON、Form) | 启用 |
143
-
144
- ## 可选扩展模块
145
-
146
- 以下模块需单独安装:
147
-
148
- - `@zenweb/cors` - 跨域支持
149
- - `@zenweb/sentry` - Sentry 错误收集
150
- - `@zenweb/metric` - 生产运行健康信息
151
- - `@zenweb/validation` - JSONSchema 验证
152
- - `@zenweb/mysql` - MySQL 数据库
153
- - `@zenweb/orm` - ORM 支持
154
- - `@zenweb/template` - 模板渲染
155
- - `@zenweb/schedule` - 定时任务
156
- - `@zenweb/form` - 统一表单
157
- - `@zenweb/grid` - 统一表格
158
- - `@zenweb/upload` - 文件上传
159
- - `@zenweb/xml-body` - XML Body 解析
160
- - `@zenweb/msgpack` - MessagePack 输出
161
-
162
- ## 全局 Helper ($前缀)
163
-
164
- 基于 AsyncLocalStorage,请求期间可在任意位置调用:
133
+ ---
134
+
135
+ ## Router 直接使用(非控制器场景)
136
+
137
+ 不使用控制器装饰器时,可直接通过 `app.router` 注册路由:
165
138
 
166
139
  ```ts
167
- // Body 解析和类型转换
168
- await $body.get({ name: 'string', age: '!int' });
169
- await $body.page({ limit: 10 });
170
- await $getObjectBody();
140
+ import { create, Router } from 'zenweb';
171
141
 
172
- // Query Param
173
- await $query.get({ id: '!int' });
174
- await $query.page();
175
- await $param.data();
142
+ const app = create({
143
+ controller: false, // 禁用控制器自动发现
144
+ });
176
145
 
177
- // 日志
178
- $log.info('message');
179
- $log.child({ extra: 'field' }).debug('debug msg');
146
+ // 直接注册路由
147
+ app.router.get('/hello', ctx => {
148
+ ctx.body = 'Hello';
149
+ });
150
+
151
+ // 子路由
152
+ const subRouter = new Router({ prefix: '/admin' });
153
+ subRouter.get('/dashboard', ctx => ctx.body = 'dashboard');
154
+ app.router.add(subRouter);
180
155
 
181
- // 上下文和 Core
182
- const ctx = $ctx;
183
- const core = $getCore();
184
- const ip = $ctx.ip;
156
+ app.start();
185
157
  ```
186
158
 
187
- ## 依赖注入
159
+ ---
160
+
161
+ ## 全局中间件
188
162
 
189
- 使用 TypeScript 装饰器(需 `experimentalDecorators` 和 `emitDecoratorMetadata`):
163
+ 通过 `setup.middleware()` 添加应用级中间件:
190
164
 
191
165
  ```ts
192
- @Injectable // 请求级服务(默认)
193
- @Injectable('singleton') // 单例服务
166
+ import { create } from 'zenweb';
167
+
168
+ const app = create();
194
169
 
195
- class MyService {
196
- constructor(private ctx: Context) {} // 自动注入 Context
170
+ // Core 级中间件(所有请求)
171
+ app.setup(function myMiddleware(setup) {
172
+ setup.middleware(async (ctx, next) => {
173
+ ctx.set('X-Custom', 'value');
174
+ return next();
175
+ });
176
+ });
177
+ ```
178
+
179
+ ---
197
180
 
198
- @Init // 初始化方法
199
- init(other: OtherService) {}
181
+ ## 消息代码(MessageCode)
200
182
 
201
- @Inject other!: OtherService; // 属性注入
183
+ 用于错误消息格式化,**优先使用统一定义文件**:
184
+
185
+ ```ts
186
+ // message-codes.json(推荐)
187
+ {
188
+ "user.notfound": "用户不存在",
189
+ "user.login.fail": "登录失败: {reason}",
190
+ "error.system": "系统错误"
202
191
  }
203
192
 
204
- // 控制器方法参数自动注入
205
- @Get()
206
- handler(service: MyService) {}
193
+ // 或 message-codes.ts
194
+ export default {
195
+ 'user.notfound': '用户不存在',
196
+ 'user.login.fail': '登录失败: {reason}',
197
+ };
198
+
199
+ // 配置(默认自动加载 ./message-codes.json)
200
+ create({
201
+ messagecode: {
202
+ autoLoadFilenames: ['./message-codes.json', './codes/custom.ts'],
203
+ },
204
+ });
205
+
206
+ // 使用
207
+ ctx.messageCodeResolver.format('user.login.fail', { reason: '密码错误' });
208
+ ctx.messageCodeResolver.fail('user.notfound'); // 直接抛出 fail 异常
207
209
  ```
208
210
 
209
- ## 控制器模式
211
+ ---
210
212
 
211
- ```ts
212
- export class UserController {
213
- @Get() // GET /user (方法名作为路径)
214
- index() { return 'list'; }
213
+ ## 依赖注入
215
214
 
216
- @Get('/:id') // GET /user/:id
217
- detail() {
218
- return $param.data(); // 获取路由参数
219
- }
215
+ **Service 类默认添加 @Injectable 注解**(将 service 类的作用域设置为 request):
220
216
 
221
- @Post() // POST /user
222
- create() {
223
- return $body.get({ name: '!string', email: 'string' });
224
- }
217
+ ```ts
218
+ @Injectable // Service 类必须添加注解!
219
+ export class UserService {
220
+ constructor(private ctx: Context, private db: DatabaseService) {} // 自动注入
221
+ }
222
+ ```
225
223
 
226
- @Put('/:id')
227
- update() {}
224
+ **无法用构造器注入时,使用 @Inject 属性注入**:
228
225
 
229
- @Delete('/:id')
230
- remove() {}
226
+ ```ts
227
+ @Injectable
228
+ export class MyService {
229
+ constructor(private ctx: Context) {} // 构造器注入
230
+
231
+ @Inject private cache!: CacheService; // 属性注入(后注入)
231
232
  }
232
233
  ```
233
234
 
234
- `controller.discoverPaths` 配置控制器目录,`autoControllerPrefix: true` 自动将文件路径映射为路由前缀。
235
+ **作用域:**
236
+ ```ts
237
+ @Injectable // 请求级(默认)
238
+ @Injectable('singleton') // 单例,不可注入 request 级依赖
239
+ @Injectable('prototype') // 每次注入创建新实例
240
+ ```
241
+
242
+ ---
243
+
244
+ ## 全局 Helper
245
+
246
+ 请求期间任意位置可用,无需注入:
247
+
248
+ ```ts
249
+ // Body
250
+ await $body.get({ name: '!string', age: 'int' });
251
+ await $body.page({ limit: 10 });
252
+
253
+ // Query
254
+ await $query.get({ id: '!int', keyword: 'trim' });
255
+ await $query.page({ allowOrder: ['id'] });
256
+
257
+ // Param(路由参数)
258
+ $ctx.params; // 原始参数对象 { id: '123' }
259
+ await $param.get({ id: '!int' }); // 带类型转换
260
+
261
+ // 日志
262
+ $log.info('message');
263
+ $log.child({ requestId: 'abc' }).debug('with context');
264
+
265
+ // 上下文
266
+ $ctx.ip; $ctx.path; $ctx.header;
267
+ $getCore().name;
268
+ ```
269
+
270
+ ---
235
271
 
236
272
  ## 错误处理
237
273
 
274
+ **fail() 用于预期业务错误**(给用户看的错误):
275
+
238
276
  ```ts
239
277
  import { fail } from 'zenweb';
240
278
 
241
- // 立即终止并返回错误响应
242
- fail('错误消息');
279
+ // 业务预期的错误,如参数验证失败、用户不存在等
280
+ fail('用户不存在');
243
281
  fail(400, '参数错误');
244
- fail({ code: 123, message: '自定义错误', status: 200 });
245
-
246
- // controller 方法 return 值自动包装为成功响应
282
+ fail({ code: 10001, message: '余额不足' });
247
283
  ```
248
284
 
249
- ## TypeScript 配置要求
285
+ **非预期错误使用自定义异常**(如数据库连接失败、代码 bug),不要用 fail():
250
286
 
251
- ```json
252
- {
253
- "compilerOptions": {
254
- "experimentalDecorators": true,
255
- "emitDecoratorMetadata": true,
256
- "target": "ES2020",
257
- "module": "commonjs",
258
- "strict": true
287
+ ```ts
288
+ class DatabaseError extends Error {
289
+ constructor(message: string) {
290
+ super(message);
291
+ this.name = 'DatabaseError';
259
292
  }
260
293
  }
294
+
295
+ // 非预期错误,框架会返回 500 并隐藏详情
296
+ throw new DatabaseError('连接失败');
297
+ ```
298
+
299
+ **控制器 return 值通过 ctx.success(data) 输出,默认不做包装:**
300
+ ```ts
301
+ return { name: 'test' }; // → { name: 'test' }
302
+
303
+ // 如需包装需在 create() 中配置
304
+ create({
305
+ result: {
306
+ successWrap: (ctx, data) => ({ code: 0, data }),
307
+ },
308
+ });
309
+ ```
310
+
311
+ ---
312
+
313
+ ## create() 配置
314
+
315
+ ```ts
316
+ create({
317
+ global: true, // 全局实例,默认 true
318
+ core: { keys: ['secret'] },
319
+ meta: false, // 禁用模块
320
+ log: { dir: '/var/log' },
321
+ result: { failCode: 1, failStatus: 400 },
322
+ body: { limit: 1024 * 1024 },
323
+ helper: { page: { defaultLimit: 20 } },
324
+ controller: {
325
+ discoverPaths: ['./controller'],
326
+ autoControllerPrefix: true,
327
+ },
328
+ })
329
+ ```
330
+
331
+ ---
332
+
333
+ ## 集成模块
334
+
335
+ 已集成,无需单独安装:
336
+
337
+ | 模块 | 作用 |
338
+ |------|------|
339
+ | `@zenweb/core` | 核心应用 |
340
+ | `@zenweb/inject` | 依赖注入 |
341
+ | `@zenweb/router` | Trie 路由 |
342
+ | `@zenweb/controller` | 控制器装饰器 |
343
+ | `@zenweb/body` | Body 解析 |
344
+ | `@zenweb/helper` | 参数验证 |
345
+ | `@zenweb/result` | 结果处理 |
346
+ | `@zenweb/log` | 日志 |
347
+ | `@zenweb/meta` | 请求元信息 |
348
+ | `@zenweb/messagecode` | 错误消息格式化 |
349
+
350
+ **可选扩展:**
351
+
352
+ | 模块 | 作用 |
353
+ |------|------|
354
+ | `@zenweb/cors` | 跨域支持 |
355
+ | `@zenweb/sentry` | Sentry 错误收集 |
356
+ | `@zenweb/metric` | 运行健康信息 |
357
+ | `@zenweb/mysql` | MySQL 数据库 |
358
+ | `@zenweb/tenant` | 多租户数据库连接池 |
359
+ | `@zenweb/orm` | ORM 支持 |
360
+ | `@zenweb/template` | 模版渲染 |
361
+ | `@zenweb/schedule` | 定时任务 |
362
+ | `@zenweb/upload` | 文件上传 |
363
+ | `@zenweb/cache` | Redis 缓存支持 |
364
+ | `@zenweb/cache-opt` | Redis 缓存优化 |
365
+ | `@zenweb/msgpack` | MessagePack 输出 |
366
+ | `@zenweb/ratelimit` | 请求量控制(防CC攻击) |
367
+ | `@zenweb/websocket` | WebSocket 支持 |
368
+ | `@zenweb/xml-body` | XML Body 解析 |
369
+ | `@zenweb/form` | 表单构建 |
370
+ | `@zenweb/grid` | 数据表渲染 |
371
+
372
+ ---
373
+
374
+ ## 类型转换语法
375
+
376
+ ```ts
377
+ await $body.get({
378
+ name: '!string', // 必填字符串
379
+ age: 'int', // 可选整数
380
+ tags: 'string[]', // 字符串数组
381
+ active: '!bool', // 必填布尔
382
+ email: 'trim', // 去空格
383
+ });
261
384
  ```
262
385
 
263
- ## 各模块 AGENTS.md 位置
386
+ 支持类型:`int`, `float`, `number`, `bool`, `string`, `trim`, `date`, `datetime`, `array`, `object`, `json`
387
+
388
+ ---
264
389
 
265
- 安装后可读取以下文件获取详细 API:
390
+ ## 各模块详细文档
391
+
392
+ 详细 API 参阅各模块 AGENTS.md:
266
393
 
267
394
  - `node_modules/@zenweb/core/AGENTS.md`
268
- - `node_modules/@zenweb/meta/AGENTS.md`
269
395
  - `node_modules/@zenweb/inject/AGENTS.md`
396
+ - `node_modules/@zenweb/controller/AGENTS.md`
397
+ - `node_modules/@zenweb/body/AGENTS.md`
398
+ - `node_modules/@zenweb/helper/AGENTS.md`
399
+ - `node_modules/@zenweb/result/AGENTS.md`
270
400
  - `node_modules/@zenweb/router/AGENTS.md`
271
401
  - `node_modules/@zenweb/log/AGENTS.md`
272
- - `node_modules/@zenweb/result/AGENTS.md`
402
+ - `node_modules/@zenweb/meta/AGENTS.md`
273
403
  - `node_modules/@zenweb/messagecode/AGENTS.md`
274
- - `node_modules/@zenweb/controller/AGENTS.md`
275
- - `node_modules/@zenweb/helper/AGENTS.md`
276
- - `node_modules/@zenweb/body/AGENTS.md`
404
+
405
+ ---
406
+
407
+ ## AI 使用要点
408
+
409
+ 1. **已集成模块从 zenweb 导入**,可选模块(cors, mysql, orm 等)从各自模块导入
410
+ ```ts
411
+ import { Injectable, Context, fail } from 'zenweb'; // 集成模块
412
+ import { MySQL } from '@zenweb/mysql'; // 可选模块
413
+ ```
414
+ 2. 优先用全局 Helper `$body/$query/$param/$log`,比 DI 更简洁
415
+ 3. **Service 类必须添加 @Injectable 注解**,优先用构造器参数注入
416
+ 4. 必填字段用 `!` 前缀,避免空值问题
417
+ 5. 单例服务不可依赖 Context,用方法参数传递
418
+ 6. 控制器文件名映射路由前缀(`autoControllerPrefix: true`)
419
+ 7. `fail()` 仅用于预期业务错误(给用户看),非预期错误用自定义异常
package/README.md CHANGED
@@ -1,135 +1,170 @@
1
1
  # ZenWeb
2
2
 
3
- Modular lightweight web framework based on Koa
3
+ 基于 Koa 的模块化轻量级 Web 框架。
4
4
 
5
- ## Document
5
+ ## 特性
6
+
7
+ - **开箱即用** - `create()` 整合多个模块,无需逐个安装
8
+ - **全局 Helper** - `$body/$query/$param/$log` 在请求期间任意位置可用
9
+ - **装饰器驱动** - TypeScript 装饰器实现控制器路由和依赖注入
10
+ - **统一响应** - `fail()` 处理业务错误,控制器 return 自动输出
11
+
12
+ ## 文档
6
13
 
7
14
  [ZenWeb 文档](https://zenweb.node.ltd)
8
15
 
9
- ## Install
16
+ ## 安装
10
17
 
11
18
  ```bash
12
- # for production
13
19
  npm i zenweb
14
20
 
15
- # for development
21
+ # 开发依赖
16
22
  npm i -D dotenv typescript rimraf tsc-watch
17
23
  ```
18
24
 
19
- ## Project Code
20
-
21
- edit `package.json` file at `scripts`:
22
-
23
- ```json
24
- "scripts": {
25
- "start": "node --enable-source-maps app",
26
- "dev": "rimraf app && tsc-watch --onSuccess \"npm run dev-start\"",
27
- "dev-start": "node -r dotenv/config --enable-source-maps app",
28
- "build": "rimraf app && tsc"
29
- }
30
- ```
25
+ ## TypeScript 配置(必需)
31
26
 
32
- create `tsconfig.json` file
27
+ 装饰器功能需要以下配置:
33
28
 
34
29
  ```json
35
30
  {
36
- {
37
31
  "compilerOptions": {
38
32
  "experimentalDecorators": true,
39
33
  "emitDecoratorMetadata": true,
40
34
  "target": "ES2020",
41
- "module": "commonjs",
42
- "types": [ "node" ],
43
- "esModuleInterop": true,
44
- "strict": true,
45
- "sourceMap": true,
46
- "newLine": "lf",
47
- "rootDir": "src",
48
- "outDir": "app"
49
- },
50
- "include": ["src/**/*"]
35
+ "module": "commonjs"
36
+ }
51
37
  }
52
38
  ```
53
39
 
54
- create `.env` file
40
+ ## 快速开始
55
41
 
56
- ```bash
57
- APP_NAME=myweb
58
- NODE_ENV=development
59
- DEBUG=*
42
+ ```ts
43
+ import { create } from 'zenweb';
44
+
45
+ create({
46
+ controller: {
47
+ discoverPaths: ['./controller'],
48
+ autoControllerPrefix: true,
49
+ },
50
+ }).start();
60
51
  ```
61
52
 
62
- create `src/index.ts` file
53
+ ## 控制器
54
+
55
+ 文件名映射为路由前缀(开启 `autoControllerPrefix`):
63
56
 
64
57
  ```ts
65
- import { create } from 'zenweb';
66
- create().start();
58
+ // controller/user.ts /user
59
+ import { Get, Post, Context } from 'zenweb';
60
+ import { UserService } from '../service/user';
61
+
62
+ export class UserController {
63
+ constructor(private ctx: Context) {}
64
+
65
+ @Get() // GET /user
66
+ list() { return []; }
67
+
68
+ @Get('/:id') // GET /user/:id
69
+ detail() {
70
+ const { id } = this.ctx.params;
71
+ return { id };
72
+ }
73
+
74
+ @Post() // POST /user
75
+ create(service: UserService) {
76
+ return service.create();
77
+ }
78
+ }
67
79
  ```
68
80
 
69
- create `src/service/hello.ts` file
81
+ ## Service
82
+
83
+ Service 类添加 `@Injectable` 注解,作用域为请求级:
70
84
 
71
85
  ```ts
86
+ // service/user.ts
72
87
  import { Injectable, Context } from 'zenweb';
73
88
 
74
89
  @Injectable
75
- export class HelloService {
76
- constructor(
77
- private ctx: Context,
78
- ){}
90
+ export class UserService {
91
+ constructor(private ctx: Context) {}
79
92
 
80
- getIp() {
81
- return this.ctx.ip;
93
+ create() {
94
+ return { ip: this.ctx.ip };
82
95
  }
83
96
  }
84
97
  ```
85
98
 
86
- create `src/controller/hello.ts` file
99
+ ## 全局 Helper
100
+
101
+ 请求期间无需注入,直接使用:
87
102
 
88
103
  ```ts
89
- import { Get } from 'zenweb';
90
- import { HelloService } from '../service/hello';
91
-
92
- export class HelloController {
93
- @Get()
94
- index(service: HelloService) {
95
- const ip = service.getIp();
96
- return `Hello ZenWeb! ${ip}`;
97
- }
98
- }
104
+ // Body 解析
105
+ await $body.get({ name: '!string', age: 'int' });
106
+
107
+ // Query 参数
108
+ await $query.get({ id: '!int', keyword: 'trim' });
109
+
110
+ // 路由参数
111
+ const { id } = $ctx.params;
112
+
113
+ // 日志
114
+ $log.info('message');
99
115
  ```
100
116
 
101
- start server:
117
+ ## 错误处理
102
118
 
103
- ```bash
104
- npm run dev
119
+ `fail()` 用于预期业务错误:
120
+
121
+ ```ts
122
+ import { fail } from 'zenweb';
123
+
124
+ if (!user) {
125
+ fail('用户不存在'); // 返回错误响应,终止执行
126
+ }
105
127
  ```
106
128
 
129
+ 非预期错误(代码 bug、数据库连接失败等)直接抛出 Error,框架返回 500。
130
+
107
131
  ## 集成模块
108
- - [core](https://www.npmjs.com/package/@zenweb/core) 核心
109
- - [meta](https://www.npmjs.com/package/@zenweb/meta) 运行基本信息,例如:请求耗时
110
- - [inject](https://www.npmjs.com/package/@zenweb/inject) 注入支持
111
- - [router](https://www.npmjs.com/package/@zenweb/router) 路由支持
112
- - [log](https://www.npmjs.com/package/@zenweb/log) 日志支持
113
- - [result](https://www.npmjs.com/package/@zenweb/result) 统一结果返回,成功或失败
114
- - [messagecode](https://www.npmjs.com/package/@zenweb/messagecode) 统一错误消息格式化
115
- - [controller](https://www.npmjs.com/package/@zenweb/controller) 类控制器支持
116
- - [helper](https://www.npmjs.com/package/@zenweb/helper) 输入数据验证助手
117
- - [body](https://www.npmjs.com/package/@zenweb/body) 请求主体解析,JSON、Form
118
132
 
119
- 集成模块默认开启,可以通过设置配置项为 **false** 关闭
133
+ 已集成,无需单独安装:
120
134
 
135
+ | 模块 | 作用 |
136
+ |------|------|
137
+ | `@zenweb/core` | 核心应用 |
138
+ | `@zenweb/inject` | 依赖注入 |
139
+ | `@zenweb/router` | Trie 路由 |
140
+ | `@zenweb/controller` | 控制器装饰器 |
141
+ | `@zenweb/body` | Body 解析 |
142
+ | `@zenweb/helper` | 参数验证 |
143
+ | `@zenweb/result` | 结果处理 |
144
+ | `@zenweb/log` | 日志 |
145
+ | `@zenweb/meta` | 请求元信息 |
146
+ | `@zenweb/messagecode` | 错误消息格式化 |
147
+
148
+ 集成模块默认开启,可通过配置项设为 `false` 关闭。
121
149
 
122
150
  ## 可选模块
123
- - [cors](https://www.npmjs.com/package/@zenweb/cors) 跨域支持
124
- - [sentry](https://www.npmjs.com/package/@zenweb/sentry) sentry 错误收集
125
- - [metric](https://www.npmjs.com/package/@zenweb/metric) 生产运行健康信息收集
126
- - [validation](https://www.npmjs.com/package/@zenweb/validation) JSONSchema 验证
127
- - [mysql](https://www.npmjs.com/package/@zenweb/mysql) MySQL 数据库支持
128
- - [orm](https://www.npmjs.com/package/@zenweb/orm) ORM 支持
129
- - [template](https://www.npmjs.com/package/@zenweb/template) 模版渲染
130
- - [schedule](https://www.npmjs.com/package/@zenweb/schedule) 定时任务
131
- - [form](https://www.npmjs.com/package/@zenweb/form) 统一表单(多用于后台)
132
- - [grid](https://www.npmjs.com/package/@zenweb/grid) 统一表格(多用于后台)
133
- - [upload](https://www.npmjs.com/package/@zenweb/upload) 文件上传支持
134
- - [xmlBody](https://www.npmjs.com/package/@zenweb/xml-body) XML Body 解析
135
- - [msgpack](https://www.npmjs.com/package/@zenweb/msgpack) MessagePack 输出
151
+
152
+ | 模块 | 作用 |
153
+ |------|------|
154
+ | `@zenweb/cors` | 跨域支持 |
155
+ | `@zenweb/sentry` | Sentry 错误收集 |
156
+ | `@zenweb/metric` | 运行健康信息 |
157
+ | `@zenweb/mysql` | MySQL 数据库 |
158
+ | `@zenweb/tenant` | 多租户数据库连接池 |
159
+ | `@zenweb/orm` | ORM 支持 |
160
+ | `@zenweb/template` | 模版渲染 |
161
+ | `@zenweb/schedule` | 定时任务 |
162
+ | `@zenweb/upload` | 文件上传 |
163
+ | `@zenweb/cache` | Redis 缓存支持 |
164
+ | `@zenweb/cache-opt` | Redis 缓存优化 |
165
+ | `@zenweb/msgpack` | `@zenweb/result` MessagePack 支持 |
166
+ | `@zenweb/ratelimit` | 请求量控制(防CC攻击) |
167
+ | `@zenweb/websocket` | WebSocket 支持(分布式会话共享) |
168
+ | `@zenweb/xml-body` | `@zenweb/body` XML 解析支持 |
169
+ | `@zenweb/form` | 表单构建 |
170
+ | `@zenweb/grid` | 数据表渲染 |
package/TEMPLATE.md ADDED
@@ -0,0 +1,231 @@
1
+ # TEMPLATE.md
2
+
3
+ AI 编程脚手架模板 - 创建 ZenWeb 项目时使用此结构。
4
+
5
+ ---
6
+
7
+ ## 项目结构
8
+
9
+ ```
10
+ project/
11
+ ├── src/
12
+ │ ├── index.ts # 应用入口
13
+ │ ├── controller/ # 控制器目录
14
+ │ │ └── index.ts # 根路由控制器
15
+ │ ├── service/ # 服务目录
16
+ │ ├── message-codes.json # 错误消息定义(可选)
17
+ │ └── types.ts # 类型定义(可选)
18
+ ├── package.json
19
+ ├── tsconfig.json
20
+ ├── .env # 开发环境变量
21
+ └── .gitignore
22
+ ```
23
+
24
+ ---
25
+
26
+ ## package.json
27
+
28
+ ```json
29
+ {
30
+ "name": "myapp",
31
+ "version": "1.0.0",
32
+ "main": "app/index.js",
33
+ "scripts": {
34
+ "build": "rimraf app && tsc",
35
+ "start": "node --enable-source-maps app",
36
+ "dev-start": "node --env-file=.env --enable-source-maps app",
37
+ "dev": "rimraf app && tsc-watch --onSuccess \"npm run dev-start\""
38
+ },
39
+ "dependencies": {
40
+ "zenweb": "^6.5.0"
41
+ },
42
+ "devDependencies": {
43
+ "@types/node": "^16",
44
+ "rimraf": "^6",
45
+ "typescript": "^6",
46
+ "tsc-watch": "^6"
47
+ }
48
+ }
49
+ ```
50
+
51
+ ---
52
+
53
+ ## tsconfig.json
54
+
55
+ ```json
56
+ {
57
+ "compilerOptions": {
58
+ "experimentalDecorators": true,
59
+ "emitDecoratorMetadata": true,
60
+ "target": "ES2020",
61
+ "module": "commonjs",
62
+ "types": ["node"],
63
+ "esModuleInterop": true,
64
+ "strict": true,
65
+ "sourceMap": true,
66
+ "rootDir": "src",
67
+ "outDir": "app"
68
+ },
69
+ "include": ["src/**/*"]
70
+ }
71
+ ```
72
+
73
+ ---
74
+
75
+ ## .env(开发环境)
76
+
77
+ ```bash
78
+ APP_NAME=myapp
79
+ NODE_ENV=development
80
+ DEBUG=*
81
+ LOG_DIR=./logs
82
+ ```
83
+
84
+ ---
85
+
86
+ ## .gitignore
87
+
88
+ ```
89
+ .env
90
+ app/
91
+ logs/
92
+ node_modules/
93
+ ```
94
+
95
+ ---
96
+
97
+ ## src/index.ts(入口文件)
98
+
99
+ ```ts
100
+ import { create } from 'zenweb';
101
+
102
+ create({
103
+ controller: {
104
+ discoverPaths: ['./controller'],
105
+ autoControllerPrefix: true,
106
+ },
107
+ }).start();
108
+ ```
109
+
110
+ ---
111
+
112
+ ## src/controller/index.ts(根路由)
113
+
114
+ ```ts
115
+ export class IndexController {
116
+ index() {
117
+ return 'Hello ZenWeb!';
118
+ }
119
+ }
120
+ ```
121
+
122
+ ---
123
+
124
+ ## src/controller/user.ts(示例控制器)
125
+
126
+ ```ts
127
+ import { Get, Post, Context, $param, $body } from 'zenweb';
128
+ import { UserService } from '../service/user';
129
+
130
+ export class UserController {
131
+ constructor(private ctx: Context) {}
132
+
133
+ @Get()
134
+ list(service: UserService) {
135
+ return service.list();
136
+ }
137
+
138
+ @Get('/:id')
139
+ async detail() {
140
+ const { id } = await $param.get({ id: '!int' });
141
+ return { id };
142
+ }
143
+
144
+ @Post()
145
+ async create(service: UserService) {
146
+ const data = await $body.get({ name: '!string', email: 'string' });
147
+ return service.create(data);
148
+ }
149
+ }
150
+ ```
151
+
152
+ ---
153
+
154
+ ## src/service/user.ts(示例服务)
155
+
156
+ ```ts
157
+ import { Injectable, Context } from 'zenweb';
158
+
159
+ @Injectable
160
+ export class UserService {
161
+ constructor(private ctx: Context) {}
162
+
163
+ list() {
164
+ return [];
165
+ }
166
+
167
+ create(data: { name: string; email?: string }) {
168
+ return { ...data, ip: this.ctx.ip };
169
+ }
170
+ }
171
+ ```
172
+
173
+ ---
174
+
175
+ ## src/message-codes.json(错误消息)
176
+
177
+ ```json
178
+ {
179
+ "user.notfound": "用户不存在",
180
+ "user.login.fail": "登录失败: {reason}"
181
+ }
182
+ ```
183
+
184
+ ---
185
+
186
+ ## 命名规范
187
+
188
+ | 类型 | 文件名 | 导出名 |
189
+ |------|--------|--------|
190
+ | 控制器 | `{name}.ts` | `{Name}Controller` |
191
+ | 服务 | `{name}.ts` | `{Name}Service` |
192
+ | 类型定义 | `types.ts` | 自由命名 |
193
+
194
+ ---
195
+
196
+ ## 路由映射规则(autoControllerPrefix: true)
197
+
198
+ | 文件路径 | 路由前缀 |
199
+ |----------|----------|
200
+ | `controller/index.ts` | `/` |
201
+ | `controller/user.ts` | `/user` |
202
+ | `controller/admin/index.ts` | `/admin` |
203
+ | `controller/admin/user.ts` | `/admin/user` |
204
+
205
+ ---
206
+
207
+ ## 可选模块扩展
208
+
209
+ 询问用户是否需要以下可选模块,如需要则安装并阅读对应模块的 AGENTS.md 文档进行配置:
210
+
211
+ | 模块 | 作用 |
212
+ |------|------|
213
+ | `@zenweb/cors` | 跨域支持 |
214
+ | `@zenweb/sentry` | Sentry 错误收集 |
215
+ | `@zenweb/metric` | 运行健康信息 |
216
+ | `@zenweb/mysql` | MySQL 数据库 |
217
+ | `@zenweb/tenant` | 多租户数据库连接池 |
218
+ | `@zenweb/orm` | ORM 支持 |
219
+ | `@zenweb/template` | 模版渲染 |
220
+ | `@zenweb/schedule` | 定时任务 |
221
+ | `@zenweb/upload` | 文件上传 |
222
+ | `@zenweb/cache` | Redis 缓存支持 |
223
+ | `@zenweb/cache-opt` | Redis 缓存优化 |
224
+ | `@zenweb/msgpack` | MessagePack 输出 |
225
+ | `@zenweb/ratelimit` | 请求量控制(防CC攻击) |
226
+ | `@zenweb/websocket` | WebSocket 支持 |
227
+ | `@zenweb/xml-body` | XML Body 解析 |
228
+ | `@zenweb/form` | 表单构建 |
229
+ | `@zenweb/grid` | 数据表渲染 |
230
+
231
+ **配置指引:** 安装后阅读 `node_modules/{模块名}/AGENTS.md` 获取详细配置说明。
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "zenweb",
3
- "version": "6.4.0",
3
+ "version": "6.5.0",
4
4
  "description": "Modular lightweight web framework based on Koa",
5
5
  "main": "dist/index.js",
6
6
  "typings": "./dist/index.d.ts",
7
7
  "files": [
8
8
  "AGENTS.md",
9
+ "TEMPLATE.md",
9
10
  "dist"
10
11
  ],
11
12
  "scripts": {
@@ -28,16 +29,16 @@
28
29
  "license": "MIT",
29
30
  "homepage": "https://zenweb.node.ltd",
30
31
  "dependencies": {
31
- "@zenweb/body": "^5.4.1",
32
- "@zenweb/controller": "^6.4.0",
33
- "@zenweb/core": "^5.3.0",
34
- "@zenweb/helper": "^5.4.0",
35
- "@zenweb/inject": "^5.4.0",
36
- "@zenweb/log": "^5.2.0",
37
- "@zenweb/messagecode": "^5.5.0",
38
- "@zenweb/meta": "^5.2.0",
39
- "@zenweb/result": "^5.3.0",
40
- "@zenweb/router": "^6.5.0"
32
+ "@zenweb/body": "^5.5.0",
33
+ "@zenweb/controller": "^6.6.0",
34
+ "@zenweb/core": "^5.4.0",
35
+ "@zenweb/helper": "^5.5.0",
36
+ "@zenweb/inject": "^5.5.0",
37
+ "@zenweb/log": "^5.3.1",
38
+ "@zenweb/messagecode": "^5.6.0",
39
+ "@zenweb/meta": "^5.3.0",
40
+ "@zenweb/result": "^5.4.0",
41
+ "@zenweb/router": "^6.6.0"
41
42
  },
42
43
  "devDependencies": {
43
44
  "@types/node": "^16.18.126",