@fastcar/cli 0.1.3 → 0.1.4

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.
@@ -1,576 +1,577 @@
1
- ---
2
- name: fastcar-framework
3
- description: FastCar 是一个基于 TypeScript 的 Node.js 企业级应用开发框架,采用 IoC(控制反转)设计思想。Use when working with FastCar framework for: (1) Creating IoC-based Node.js applications, (2) Using dependency injection with decorators (@Component, @Service, @Autowired), (3) Building web APIs with @fastcar/koa, (4) Database operations with MySQL/MongoDB/Redis, (5) Setting up scheduled tasks or worker pools, (6) Managing application lifecycle and configuration.
4
- ---
5
-
6
- # FastCar Framework
7
-
8
- FastCar 是基于 TypeScript 的 Node.js 企业级应用开发框架,采用 IoC(控制反转)设计思想。
9
-
10
- ## 核心概念
11
-
12
- ### IoC 容器与装饰器
13
-
14
- | 装饰器 | 用途 | 示例 |
15
- |--------|------|------|
16
- | `@Application` | 入口应用类 | `@Application class App {}` |
17
- | `@Component` | 通用组件 | `@Component class UtilService {}` |
18
- | `@Service` | 服务层 | `@Service class BizService {}` |
19
- | `@Controller` | 控制器层 | `@Controller class ApiController {}` |
20
- | `@Repository` | 数据访问层 | `@Repository class DataRepository {}` |
21
- | `@Autowired` | 依赖注入 | `@Autowired private service!: BizService;` |
22
-
23
- ### 基础应用结构
24
-
25
- ```typescript
26
- import { FastCarApplication } from "@fastcar/core";
27
- import { Application, Autowired, Component, Service, Controller } from "@fastcar/core/annotation";
28
-
29
- @Service
30
- class BizService {
31
- getData() {
32
- return [{ id: 1, name: "示例" }];
33
- }
34
- }
35
-
36
- @Controller
37
- class ApiController {
38
- @Autowired
39
- private service!: BizService;
40
-
41
- getData() {
42
- return this.service.getData();
43
- }
44
- }
45
-
46
- @Application
47
- class App {
48
- app!: FastCarApplication;
49
-
50
- async start() {
51
- console.log("应用启动成功!");
52
- }
53
- }
54
-
55
- const app = new App();
56
- app.start();
57
- ```
58
-
59
- ## 模块速查
60
-
61
- ### Web 开发 (@fastcar/koa)
62
-
63
- **路由装饰器使用方式:**
64
-
65
- ```typescript
66
- import { GET, POST, REQUEST } from "@fastcar/koa/annotation";
67
-
68
- @Controller
69
- @REQUEST("/api/items")
70
- class ItemController {
71
- // GET 请求 - 无路径参数时必须有括号
72
- @GET()
73
- async list() {
74
- return { data: [] };
75
- }
76
-
77
- // GET 请求 - 有路径参数
78
- @GET("/:id")
79
- async getById(id: string) {
80
- return { id };
81
- }
82
-
83
- // POST 请求
84
- @POST()
85
- async create(body: ItemDTO) {
86
- return { created: true };
87
- }
88
- }
89
- ```
90
-
91
- **⚠️ 重要:FastCar 没有 `@Body`, `@Param`, `@Query` 装饰器**
92
-
93
- - 请求参数直接作为方法参数传入
94
- - GET 请求参数通过方法参数直接获取
95
- - POST 请求体通过 `body` 参数获取
96
- - 路径参数通过方法参数直接获取
97
-
98
- ### 数据库 (@fastcar/mysql)
99
-
100
- **实体定义:**
101
-
102
- ```typescript
103
- import { Table, Field, DBType, PrimaryKey, NotNull, Size } from "@fastcar/core/annotation";
104
-
105
- @Table("entities")
106
- class Entity {
107
- @Field("id")
108
- @DBType("int")
109
- @PrimaryKey
110
- id!: number;
111
-
112
- @Field("name")
113
- @DBType("varchar")
114
- @NotNull
115
- @Size({ maxSize: 50 })
116
- name!: string;
117
- }
118
- ```
119
-
120
- **Mapper 定义:**
121
-
122
- ```typescript
123
- import { Entity, Repository } from "@fastcar/core/annotation";
124
- import { MysqlMapper } from "@fastcar/mysql";
125
-
126
- @Entity(Entity)
127
- @Repository
128
- class EntityMapper extends MysqlMapper<Entity> {}
129
- export default EntityMapper;
130
- ```
131
-
132
- **Service 中使用:**
133
-
134
- ```typescript
135
- import { Service, Autowired } from "@fastcar/core/annotation";
136
- import { OrderEnum } from "@fastcar/core/db";
137
- import EntityMapper from "./EntityMapper";
138
-
139
- @Service
140
- class EntityService {
141
- @Autowired
142
- private mapper!: EntityMapper;
143
-
144
- async getList() {
145
- return this.mapper.select({
146
- where: { status: 1 },
147
- orders: { createTime: OrderEnum.desc },
148
- limit: 10
149
- });
150
- }
151
-
152
- async getOne(id: number) {
153
- return this.mapper.selectOne({ where: { id } });
154
- }
155
-
156
- async create(data: Entity) {
157
- return this.mapper.saveOne(data);
158
- }
159
-
160
- async update(id: number, data: Partial<Entity>) {
161
- return this.mapper.update({ where: { id }, row: data });
162
- }
163
-
164
- async delete(id: number) {
165
- return this.mapper.delete({ where: { id } });
166
- }
167
- }
168
- ```
169
-
170
- ### 表单验证 (@fastcar/core)
171
-
172
- ```typescript
173
- import { ValidForm, NotNull, Size, Rule } from "@fastcar/core/annotation";
174
-
175
- class ItemDTO {
176
- @NotNull
177
- name!: string;
178
-
179
- @Size({ minSize: 1, maxSize: 150 })
180
- value!: number;
181
- }
182
-
183
- @Controller
184
- @REQUEST("/api/items")
185
- class ItemController {
186
- @GET()
187
- async list(page: number = 1, pageSize: number = 10) {
188
- return { page, pageSize, data: [] };
189
- }
190
-
191
- @ValidForm
192
- @POST()
193
- async create(@Rule() body: ItemDTO) {
194
- const { name, value } = body;
195
- return this.service.create({ name, value });
196
- }
197
- }
198
- ```
199
-
200
- **表单验证规则:**
201
-
202
- | 装饰器 | 用途 | 示例 |
203
- |--------|------|------|
204
- | `@ValidForm` | 开启方法参数校验 | 放在方法上 |
205
- | `@Rule()` | 标记校验对象 | 放在 DTO 参数前 |
206
- | `@NotNull` | 参数不能为空 | 放在 DTO 字段上 |
207
- | `@Size({min, max})` | 大小限制 | 放在 DTO 字段上 |
208
-
209
- ### Redis (@fastcar/redis)
210
-
211
- ```typescript
212
- import { Service, Autowired } from "@fastcar/core/annotation";
213
- import { RedisClient } from "@fastcar/redis/annotation";
214
-
215
- @Service
216
- class CacheService {
217
- @RedisClient
218
- private redis!: RedisClient;
219
-
220
- async get(key: string) {
221
- return this.redis.get(key);
222
- }
223
-
224
- async set(key: string, value: string, ttl?: number) {
225
- await this.redis.set(key, value, ttl);
226
- }
227
- }
228
- ```
229
-
230
- ### 定时任务 (@fastcar/timer)
231
-
232
- > **推荐使用 `@fastcar/timer/scheduling2` 模块**
233
-
234
- ```typescript
235
- import { ScheduledInterval, ScheduledCron } from "@fastcar/timer/scheduling2";
236
-
237
- @Component
238
- class TaskService {
239
- // 间隔执行(毫秒)
240
- @ScheduledInterval({ fixedRate: 60000 })
241
- async intervalTask() {
242
- console.log("每分钟执行");
243
- }
244
-
245
- // Cron 表达式
246
- @ScheduledCron("0 0 * * * *")
247
- async hourlyTask() {
248
- console.log("每小时执行");
249
- }
250
- }
251
- ```
252
-
253
- ### 工作线程池 (@fastcar/workerpool)
254
-
255
- ```typescript
256
- import { WorkerPool, WorkerTask } from "@fastcar/workerpool/annotation";
257
-
258
- @Component
259
- class ComputeService {
260
- @WorkerPool({ minWorkers: 2, maxWorkers: 4 })
261
- private pool!: WorkerPool;
262
-
263
- @WorkerTask
264
- heavyComputation(data: number[]): number {
265
- return data.reduce((a, b) => a + b, 0);
266
- }
267
- }
268
- ```
269
-
270
- ## 项目模板速查
271
-
272
- FastCar CLI 提供 5 种项目模板:
273
-
274
- | 模板 | 适用场景 | 核心依赖 | 关键注解 |
275
- |------|---------|---------|---------|
276
- | web | RESTful API 服务 | @fastcar/koa, @fastcar/server | @EnableKoa |
277
- | static | 静态资源服务器 | @fastcar/koa, @fastcar/server | @EnableKoa + KoaStatic |
278
- | rpc | RPC 微服务通信 | @fastcar/rpc, @fastcar/server | @EnableRPC |
279
- | cos | 对象存储/文件上传 | @fastcar/koa, @fastcar/cossdk, @fastcar/server | @EnableKoa |
280
- | microservices | 分布式多服务架构 | @fastcar/koa, @fastcar/rpc, @fastcar/server, @fastcar/timer | @EnableKoa / @EnableRPC |
281
-
282
- ### 各模板入口示例
283
-
284
- **Web 模板**
285
- ```typescript
286
- import { Application } from "@fastcar/core/annotation";
287
- import { EnableKoa, KoaMiddleware } from "@fastcar/koa/annotation";
288
- import { ExceptionGlobalHandler, KoaBodyParser } from "@fastcar/koa";
289
-
290
- @Application
291
- @EnableKoa
292
- @KoaMiddleware(ExceptionGlobalHandler)
293
- @KoaMiddleware(KoaBodyParser)
294
- class APP {
295
- app!: FastCarApplication;
296
- }
297
- export default new APP();
298
- ```
299
-
300
- **RPC 模板**
301
- ```typescript
302
- import { Application } from "@fastcar/core/annotation";
303
- import { EnableRPC } from "@fastcar/rpc/annotation";
304
-
305
- @Application
306
- @EnableRPC
307
- class APP {}
308
- export default new APP();
309
- ```
310
-
311
- **Microservices 模板**
312
- 微服务模板包含多服务架构:center(服务中心)、connector(连接器)、message(消息服务)、web(Web服务)、base(基础服务)。
313
-
314
- ### 项目结构示例
315
-
316
- ```
317
- template/
318
- ├── src/
319
- ├── controller/ # 控制器(web/cos)
320
- │ ├── dto/ # DTO 类(表单验证)
321
- │ ├── service/ # 服务层
322
- │ ├── model/ # 数据模型
323
- └── app.ts # 应用入口
324
- ├── resource/
325
- │ └── application.yml # 配置文件
326
- ├── package.json
327
- └── tsconfig.json
328
- ```
329
-
330
- ### 模板依赖安装
331
-
332
- ```bash
333
- # Web / Static
334
- npm i @fastcar/core @fastcar/koa @fastcar/server
335
-
336
- # RPC
337
- npm i @fastcar/core @fastcar/rpc @fastcar/server
338
-
339
- # COS
340
- npm i @fastcar/core @fastcar/koa @fastcar/cossdk @fastcar/server
341
-
342
- # Microservices
343
- npm i @fastcar/core @fastcar/koa @fastcar/rpc @fastcar/server @fastcar/timer
344
- ```
345
-
346
- ## 配置管理
347
-
348
- 配置文件放在 `resource/application.yml`。支持按 `env` 加载多文件,例如 `application-dev.yml` 会与主配置合并。
349
-
350
- ### 基础配置示例
351
-
352
- ```yaml
353
- application:
354
- name: my-app
355
- version: 1.0.0
356
- env: dev
357
-
358
- mysql:
359
- host: localhost
360
- port: 3306
361
- database: mydb
362
- username: root
363
- password: password
364
-
365
- redis:
366
- host: localhost
367
- port: 6379
368
- ```
369
-
370
- 使用配置:
371
-
372
- ```typescript
373
- import { Configure, Value } from "@fastcar/core/annotation";
374
-
375
- @Configure
376
- class AppConfig {
377
- @Value("server.port")
378
- port!: number;
379
-
380
- @Value("mysql.host")
381
- dbHost!: string;
382
- }
383
- ```
384
-
385
- ### Web 模板 application.yml
386
-
387
- ```yaml
388
- application:
389
- env: "dev"
390
-
391
- settings:
392
- koa:
393
- server:
394
- - { port: 8080, host: "0.0.0.0" }
395
- koaStatic:
396
- { "public": "public" }
397
- koaBodyParser:
398
- enableTypes: ["json", "form", "text"]
399
- ```
400
-
401
- ### RPC 模板配置
402
-
403
- ```yaml
404
- application:
405
- name: "fastcar-boot-rpc"
406
-
407
- settings:
408
- rpc:
409
- list:
410
- - id: "server-1"
411
- type: "ws"
412
- server: { port: 1235 }
413
- serviceType: "base"
414
- secure:
415
- username: "user"
416
- password: "password"
417
- ```
418
-
419
- ### Microservices 模板配置
420
-
421
- ```yaml
422
- settings:
423
- microservices:
424
- center:
425
- token: "your-token-here"
426
- servers:
427
- - host: "localhost"
428
- clusters: 1
429
- list:
430
- - type: "ws"
431
- server: { port: 60000 }
432
- connector:
433
- token: "your-token-here"
434
- servers:
435
- - host: "localhost"
436
- clusters: 1
437
- list:
438
- - front: true
439
- type: "ws"
440
- server: { port: 60100 }
441
- ```
442
-
443
- ## 生命周期钩子
444
-
445
- ```typescript
446
- import { ApplicationStart, ApplicationStop, ApplicationInit } from "@fastcar/core/annotation";
447
-
448
- @Component
449
- class LifecycleService {
450
- @ApplicationStart
451
- async onStart() {
452
- console.log("应用启动");
453
- }
454
-
455
- @ApplicationStop
456
- async onStop() {
457
- console.log("应用停止");
458
- }
459
-
460
- @ApplicationInit
461
- async init() {
462
- console.log("初始化完成");
463
- }
464
- }
465
- ```
466
-
467
- ## 工具类
468
-
469
- ```typescript
470
- import { DateUtil, CryptoUtil, FileUtil, TypeUtil } from "@fastcar/core/utils";
471
-
472
- // 日期时间
473
- DateUtil.toDateTime(); // "2024-03-10 15:30:45"
474
- DateUtil.toDay(); // "2024-03-10"
475
-
476
- // 加密
477
- CryptoUtil.aesEncode(key, iv, "data");
478
- CryptoUtil.sha256Encode("password");
479
-
480
- // 文件操作
481
- FileUtil.getFilePathList("./src");
482
- FileUtil.getResource("./config.yml");
483
-
484
- // 类型判断
485
- TypeUtil.isFunction(() => {}); // true
486
- TypeUtil.isClass(MyClass); // true
487
- ```
488
-
489
- ## 完整模块列表
490
-
491
- | 模块 | 安装命令 | 用途 |
492
- |------|----------|------|
493
- | @fastcar/core | `npm i @fastcar/core` | IoC 容器、配置管理 |
494
- | @fastcar/koa | `npm i @fastcar/koa @fastcar/server` | Web 开发 |
495
- | @fastcar/mysql | `npm i @fastcar/mysql` | MySQL 数据库 |
496
- | @fastcar/pgsql | `npm i @fastcar/pgsql` | PostgreSQL |
497
- | @fastcar/mongo | `npm i @fastcar/mongo` | MongoDB |
498
- | @fastcar/redis | `npm i @fastcar/redis` | Redis 缓存 |
499
- | @fastcar/cache | `npm i @fastcar/cache` | 缓存组件 |
500
- | @fastcar/timer | `npm i @fastcar/timer` | 定时任务 |
501
- | @fastcar/timewheel | `npm i @fastcar/timewheel` | 时间轮延时任务 |
502
- | @fastcar/workerpool | `npm i @fastcar/workerpool` | 工作线程池 |
503
- | @fastcar/rpc | `npm i @fastcar/rpc` | RPC 通信 |
504
- | @fastcar/serverless | `npm i @fastcar/serverless` | Serverless 支持 |
505
- | @fastcar/cos-sdk | `npm i @fastcar/cos-sdk` | 对象存储 |
506
-
507
- ## 快速开始新项目
508
-
509
- ### 使用 CLI 创建项目(推荐)
510
-
511
- ```bash
512
- # Web 项目
513
- mkdir my-web-app && cd my-web-app
514
- fastcar-cli init web
515
- npm install
516
- npm run debug
517
-
518
- # RPC 项目
519
- mkdir my-rpc-app && cd my-rpc-app
520
- fastcar-cli init rpc
521
- npm install
522
- npm run debug
523
-
524
- # Microservices 项目
525
- mkdir my-ms-app && cd my-ms-app
526
- fastcar-cli init microservices
527
- npm install
528
- npm run start-node
529
- ```
530
-
531
- ## 常见错误与注意事项
532
-
533
- ### 1. 路由装饰器必须有括号
534
-
535
- ❌ **错误:**
536
- ```typescript
537
- @GET
538
- async list() { }
539
- ```
540
-
541
- ✅ **正确:**
542
- ```typescript
543
- @GET()
544
- async list() { }
545
- ```
546
-
547
- ### 2. 不要使用不存在的装饰器
548
-
549
- ❌ **错误:**
550
- ```typescript
551
- import { Body, Param, Query } from "@fastcar/koa/annotation";
552
-
553
- @GET("/:id")
554
- async getById(@Param("id") id: string) { }
555
- ```
556
-
557
- ✅ **正确:**
558
- ```typescript
559
- @GET("/:id")
560
- async getById(id: string) { }
561
- ```
562
-
563
- ### 3. 表单验证使用 @ValidForm + @Rule
564
-
565
- ❌ **错误:**
566
- ```typescript
567
- @POST()
568
- async create(@Body body: ItemDTO) { }
569
- ```
570
-
571
- ✅ **正确:**
572
- ```typescript
573
- @ValidForm
574
- @POST()
575
- async create(@Rule() body: ItemDTO) { }
576
- ```
1
+ ---
2
+ name: fastcar-framework
3
+ description: FastCar 是一个基于 TypeScript 的 Node.js 企业级应用开发框架,采用 IoC(控制反转)设计思想。Use when working with FastCar framework for: (1) Creating IoC-based Node.js applications, (2) Using dependency injection with decorators (@Component, @Service, @Autowired), (3) Building web APIs with @fastcar/koa, (4) Database operations with MySQL/MongoDB/Redis, (5) Setting up scheduled tasks or worker pools, (6) Managing application lifecycle and configuration.
4
+ ---
5
+
6
+ # FastCar Framework
7
+
8
+ FastCar 是基于 TypeScript 的 Node.js 企业级应用开发框架,采用 IoC(控制反转)设计思想。
9
+
10
+ ## 核心概念
11
+
12
+ ### IoC 容器与装饰器
13
+
14
+ | 装饰器 | 用途 | 示例 |
15
+ |--------|------|------|
16
+ | `@Application` | 入口应用类 | `@Application class App {}` |
17
+ | `@Component` | 通用组件 | `@Component class UtilService {}` |
18
+ | `@Service` | 服务层 | `@Service class BizService {}` |
19
+ | `@Controller` | 控制器层 | `@Controller class ApiController {}` |
20
+ | `@Repository` | 数据访问层 | `@Repository class DataRepository {}` |
21
+ | `@Autowired` | 依赖注入 | `@Autowired private service!: BizService;` |
22
+
23
+ ### 基础应用结构
24
+
25
+ ```typescript
26
+ import { FastCarApplication } from "@fastcar/core";
27
+ import { Application, Autowired, Component, Service, Controller } from "@fastcar/core/annotation";
28
+
29
+ @Service
30
+ class BizService {
31
+ getData() {
32
+ return [{ id: 1, name: "示例" }];
33
+ }
34
+ }
35
+
36
+ @Controller
37
+ class ApiController {
38
+ @Autowired
39
+ private service!: BizService;
40
+
41
+ getData() {
42
+ return this.service.getData();
43
+ }
44
+ }
45
+
46
+ @Application
47
+ class App {
48
+ app!: FastCarApplication;
49
+
50
+ async start() {
51
+ console.log("应用启动成功!");
52
+ }
53
+ }
54
+
55
+ const app = new App();
56
+ app.start();
57
+ ```
58
+
59
+ ## 模块速查
60
+
61
+ ### Web 开发 (@fastcar/koa)
62
+
63
+ **路由装饰器使用方式:**
64
+
65
+ ```typescript
66
+ import { GET, POST, REQUEST } from "@fastcar/koa/annotation";
67
+ import { Context } from "koa";
68
+
69
+ @Controller
70
+ @REQUEST("/api/items")
71
+ class ItemController {
72
+ // GET 请求 - 无路径参数时必须有括号
73
+ @GET()
74
+ async list() {
75
+ return { data: [] };
76
+ }
77
+
78
+ // GET 请求 - 有路径参数
79
+ @GET("/:id")
80
+ async getById(id: string, ctx: Context) {
81
+ return { id };
82
+ }
83
+
84
+ // POST 请求
85
+ @POST()
86
+ async create(body: ItemDTO, ctx: Context) {
87
+ return { created: true };
88
+ }
89
+ }
90
+ ```
91
+
92
+ **⚠️ 重要:FastCar 没有 `@Body`, `@Param`, `@Query` 装饰器**
93
+
94
+ - 请求参数直接作为方法参数传入
95
+ - 第一个参数为请求数据(GET 的 query / POST body / 路径参数)
96
+ - 第二个参数为 Koa 上下文 `ctx: Context`,**可省略**
97
+ - `Context` 需从 `koa` 导入:`import { Context } from "koa"`
98
+
99
+ ### 数据库 (@fastcar/mysql)
100
+
101
+ **实体定义:**
102
+
103
+ ```typescript
104
+ import { Table, Field, DBType, PrimaryKey, NotNull, Size } from "@fastcar/core/annotation";
105
+
106
+ @Table("entities")
107
+ class Entity {
108
+ @Field("id")
109
+ @DBType("int")
110
+ @PrimaryKey
111
+ id!: number;
112
+
113
+ @Field("name")
114
+ @DBType("varchar")
115
+ @NotNull
116
+ @Size({ maxSize: 50 })
117
+ name!: string;
118
+ }
119
+ ```
120
+
121
+ **Mapper 定义:**
122
+
123
+ ```typescript
124
+ import { Entity, Repository } from "@fastcar/core/annotation";
125
+ import { MysqlMapper } from "@fastcar/mysql";
126
+
127
+ @Entity(Entity)
128
+ @Repository
129
+ class EntityMapper extends MysqlMapper<Entity> {}
130
+ export default EntityMapper;
131
+ ```
132
+
133
+ **Service 中使用:**
134
+
135
+ ```typescript
136
+ import { Service, Autowired } from "@fastcar/core/annotation";
137
+ import { OrderEnum } from "@fastcar/core/db";
138
+ import EntityMapper from "./EntityMapper";
139
+
140
+ @Service
141
+ class EntityService {
142
+ @Autowired
143
+ private mapper!: EntityMapper;
144
+
145
+ async getList() {
146
+ return this.mapper.select({
147
+ where: { status: 1 },
148
+ orders: { createTime: OrderEnum.desc },
149
+ limit: 10
150
+ });
151
+ }
152
+
153
+ async getOne(id: number) {
154
+ return this.mapper.selectOne({ where: { id } });
155
+ }
156
+
157
+ async create(data: Entity) {
158
+ return this.mapper.saveOne(data);
159
+ }
160
+
161
+ async update(id: number, data: Partial<Entity>) {
162
+ return this.mapper.update({ where: { id }, row: data });
163
+ }
164
+
165
+ async delete(id: number) {
166
+ return this.mapper.delete({ where: { id } });
167
+ }
168
+ }
169
+ ```
170
+
171
+ ### 表单验证 (@fastcar/core)
172
+
173
+ ```typescript
174
+ import { ValidForm, NotNull, Size, Rule } from "@fastcar/core/annotation";
175
+
176
+ class ItemDTO {
177
+ @NotNull
178
+ name!: string;
179
+
180
+ @Size({ minSize: 1, maxSize: 150 })
181
+ value!: number;
182
+ }
183
+
184
+ @Controller
185
+ @REQUEST("/api/items")
186
+ class ItemController {
187
+ @GET()
188
+ async list(page: number = 1, pageSize: number = 10) {
189
+ return { page, pageSize, data: [] };
190
+ }
191
+
192
+ @ValidForm
193
+ @POST()
194
+ async create(@Rule() body: ItemDTO) {
195
+ const { name, value } = body;
196
+ return this.service.create({ name, value });
197
+ }
198
+ }
199
+ ```
200
+
201
+ **表单验证规则:**
202
+
203
+ | 装饰器 | 用途 | 示例 |
204
+ |--------|------|------|
205
+ | `@ValidForm` | 开启方法参数校验 | 放在方法上 |
206
+ | `@Rule()` | 标记校验对象 | 放在 DTO 参数前 |
207
+ | `@NotNull` | 参数不能为空 | 放在 DTO 字段上 |
208
+ | `@Size({min, max})` | 大小限制 | 放在 DTO 字段上 |
209
+
210
+ ### Redis (@fastcar/redis)
211
+
212
+ ```typescript
213
+ import { Service, Autowired } from "@fastcar/core/annotation";
214
+ import { RedisClient } from "@fastcar/redis/annotation";
215
+
216
+ @Service
217
+ class CacheService {
218
+ @RedisClient
219
+ private redis!: RedisClient;
220
+
221
+ async get(key: string) {
222
+ return this.redis.get(key);
223
+ }
224
+
225
+ async set(key: string, value: string, ttl?: number) {
226
+ await this.redis.set(key, value, ttl);
227
+ }
228
+ }
229
+ ```
230
+
231
+ ### 定时任务 (@fastcar/timer)
232
+
233
+ > **推荐使用 `@fastcar/timer/scheduling2` 模块**
234
+
235
+ ```typescript
236
+ import { ScheduledInterval, ScheduledCron } from "@fastcar/timer/scheduling2";
237
+
238
+ @Component
239
+ class TaskService {
240
+ // 间隔执行(毫秒)
241
+ @ScheduledInterval({ fixedRate: 60000 })
242
+ async intervalTask() {
243
+ console.log("每分钟执行");
244
+ }
245
+
246
+ // Cron 表达式
247
+ @ScheduledCron("0 0 * * * *")
248
+ async hourlyTask() {
249
+ console.log("每小时执行");
250
+ }
251
+ }
252
+ ```
253
+
254
+ ### 工作线程池 (@fastcar/workerpool)
255
+
256
+ ```typescript
257
+ import { WorkerPool, WorkerTask } from "@fastcar/workerpool/annotation";
258
+
259
+ @Component
260
+ class ComputeService {
261
+ @WorkerPool({ minWorkers: 2, maxWorkers: 4 })
262
+ private pool!: WorkerPool;
263
+
264
+ @WorkerTask
265
+ heavyComputation(data: number[]): number {
266
+ return data.reduce((a, b) => a + b, 0);
267
+ }
268
+ }
269
+ ```
270
+
271
+ ## 项目模板速查
272
+
273
+ FastCar CLI 提供 5 种项目模板:
274
+
275
+ | 模板 | 适用场景 | 核心依赖 | 关键注解 |
276
+ |------|---------|---------|---------|
277
+ | web | RESTful API 服务 | @fastcar/koa, @fastcar/server | @EnableKoa |
278
+ | static | 静态资源服务器 | @fastcar/koa, @fastcar/server | @EnableKoa + KoaStatic |
279
+ | rpc | RPC 微服务通信 | @fastcar/rpc, @fastcar/server | @EnableRPC |
280
+ | cos | 对象存储/文件上传 | @fastcar/koa, @fastcar/cossdk, @fastcar/server | @EnableKoa |
281
+ | microservices | 分布式多服务架构 | @fastcar/koa, @fastcar/rpc, @fastcar/server, @fastcar/timer | @EnableKoa / @EnableRPC |
282
+
283
+ ### 各模板入口示例
284
+
285
+ **Web 模板**
286
+ ```typescript
287
+ import { Application } from "@fastcar/core/annotation";
288
+ import { EnableKoa, KoaMiddleware } from "@fastcar/koa/annotation";
289
+ import { ExceptionGlobalHandler, KoaBodyParser } from "@fastcar/koa";
290
+
291
+ @Application
292
+ @EnableKoa
293
+ @KoaMiddleware(ExceptionGlobalHandler)
294
+ @KoaMiddleware(KoaBodyParser)
295
+ class APP {
296
+ app!: FastCarApplication;
297
+ }
298
+ export default new APP();
299
+ ```
300
+
301
+ **RPC 模板**
302
+ ```typescript
303
+ import { Application } from "@fastcar/core/annotation";
304
+ import { EnableRPC } from "@fastcar/rpc/annotation";
305
+
306
+ @Application
307
+ @EnableRPC
308
+ class APP {}
309
+ export default new APP();
310
+ ```
311
+
312
+ **Microservices 模板**
313
+ 微服务模板包含多服务架构:center(服务中心)、connector(连接器)、message(消息服务)、web(Web服务)、base(基础服务)。
314
+
315
+ ### 项目结构示例
316
+
317
+ ```
318
+ template/
319
+ ├── src/
320
+ │ ├── controller/ # 控制器(web/cos)
321
+ │ ├── dto/ # DTO 类(表单验证)
322
+ │ ├── service/ # 服务层
323
+ ├── model/ # 数据模型
324
+ │ └── app.ts # 应用入口
325
+ ├── resource/
326
+ │ └── application.yml # 配置文件
327
+ ├── package.json
328
+ └── tsconfig.json
329
+ ```
330
+
331
+ ### 模板依赖安装
332
+
333
+ ```bash
334
+ # Web / Static
335
+ npm i @fastcar/core @fastcar/koa @fastcar/server
336
+
337
+ # RPC
338
+ npm i @fastcar/core @fastcar/rpc @fastcar/server
339
+
340
+ # COS
341
+ npm i @fastcar/core @fastcar/koa @fastcar/cossdk @fastcar/server
342
+
343
+ # Microservices
344
+ npm i @fastcar/core @fastcar/koa @fastcar/rpc @fastcar/server @fastcar/timer
345
+ ```
346
+
347
+ ## 配置管理
348
+
349
+ 配置文件放在 `resource/application.yml`。支持按 `env` 加载多文件,例如 `application-dev.yml` 会与主配置合并。
350
+
351
+ ### 基础配置示例
352
+
353
+ ```yaml
354
+ application:
355
+ name: my-app
356
+ version: 1.0.0
357
+ env: dev
358
+
359
+ mysql:
360
+ host: localhost
361
+ port: 3306
362
+ database: mydb
363
+ username: root
364
+ password: password
365
+
366
+ redis:
367
+ host: localhost
368
+ port: 6379
369
+ ```
370
+
371
+ 使用配置:
372
+
373
+ ```typescript
374
+ import { Configure, Value } from "@fastcar/core/annotation";
375
+
376
+ @Configure
377
+ class AppConfig {
378
+ @Value("server.port")
379
+ port!: number;
380
+
381
+ @Value("mysql.host")
382
+ dbHost!: string;
383
+ }
384
+ ```
385
+
386
+ ### Web 模板 application.yml
387
+
388
+ ```yaml
389
+ application:
390
+ env: "dev"
391
+
392
+ settings:
393
+ koa:
394
+ server:
395
+ - { port: 8080, host: "0.0.0.0" }
396
+ koaStatic:
397
+ { "public": "public" }
398
+ koaBodyParser:
399
+ enableTypes: ["json", "form", "text"]
400
+ ```
401
+
402
+ ### RPC 模板配置
403
+
404
+ ```yaml
405
+ application:
406
+ name: "fastcar-boot-rpc"
407
+
408
+ settings:
409
+ rpc:
410
+ list:
411
+ - id: "server-1"
412
+ type: "ws"
413
+ server: { port: 1235 }
414
+ serviceType: "base"
415
+ secure:
416
+ username: "user"
417
+ password: "password"
418
+ ```
419
+
420
+ ### Microservices 模板配置
421
+
422
+ ```yaml
423
+ settings:
424
+ microservices:
425
+ center:
426
+ token: "your-token-here"
427
+ servers:
428
+ - host: "localhost"
429
+ clusters: 1
430
+ list:
431
+ - type: "ws"
432
+ server: { port: 60000 }
433
+ connector:
434
+ token: "your-token-here"
435
+ servers:
436
+ - host: "localhost"
437
+ clusters: 1
438
+ list:
439
+ - front: true
440
+ type: "ws"
441
+ server: { port: 60100 }
442
+ ```
443
+
444
+ ## 生命周期钩子
445
+
446
+ ```typescript
447
+ import { ApplicationStart, ApplicationStop, ApplicationInit } from "@fastcar/core/annotation";
448
+
449
+ @Component
450
+ class LifecycleService {
451
+ @ApplicationStart
452
+ async onStart() {
453
+ console.log("应用启动");
454
+ }
455
+
456
+ @ApplicationStop
457
+ async onStop() {
458
+ console.log("应用停止");
459
+ }
460
+
461
+ @ApplicationInit
462
+ async init() {
463
+ console.log("初始化完成");
464
+ }
465
+ }
466
+ ```
467
+
468
+ ## 工具类
469
+
470
+ ```typescript
471
+ import { DateUtil, CryptoUtil, FileUtil, TypeUtil } from "@fastcar/core/utils";
472
+
473
+ // 日期时间
474
+ DateUtil.toDateTime(); // "2024-03-10 15:30:45"
475
+ DateUtil.toDay(); // "2024-03-10"
476
+
477
+ // 加密
478
+ CryptoUtil.aesEncode(key, iv, "data");
479
+ CryptoUtil.sha256Encode("password");
480
+
481
+ // 文件操作
482
+ FileUtil.getFilePathList("./src");
483
+ FileUtil.getResource("./config.yml");
484
+
485
+ // 类型判断
486
+ TypeUtil.isFunction(() => {}); // true
487
+ TypeUtil.isClass(MyClass); // true
488
+ ```
489
+
490
+ ## 完整模块列表
491
+
492
+ | 模块 | 安装命令 | 用途 |
493
+ |------|----------|------|
494
+ | @fastcar/core | `npm i @fastcar/core` | IoC 容器、配置管理 |
495
+ | @fastcar/koa | `npm i @fastcar/koa @fastcar/server` | Web 开发 |
496
+ | @fastcar/mysql | `npm i @fastcar/mysql` | MySQL 数据库 |
497
+ | @fastcar/pgsql | `npm i @fastcar/pgsql` | PostgreSQL |
498
+ | @fastcar/mongo | `npm i @fastcar/mongo` | MongoDB |
499
+ | @fastcar/redis | `npm i @fastcar/redis` | Redis 缓存 |
500
+ | @fastcar/cache | `npm i @fastcar/cache` | 缓存组件 |
501
+ | @fastcar/timer | `npm i @fastcar/timer` | 定时任务 |
502
+ | @fastcar/timewheel | `npm i @fastcar/timewheel` | 时间轮延时任务 |
503
+ | @fastcar/workerpool | `npm i @fastcar/workerpool` | 工作线程池 |
504
+ | @fastcar/rpc | `npm i @fastcar/rpc` | RPC 通信 |
505
+ | @fastcar/serverless | `npm i @fastcar/serverless` | Serverless 支持 |
506
+ | @fastcar/cos-sdk | `npm i @fastcar/cos-sdk` | 对象存储 |
507
+
508
+ ## 快速开始新项目
509
+
510
+ ### 使用 CLI 创建项目(推荐)
511
+
512
+ ```bash
513
+ # Web 项目
514
+ mkdir my-web-app && cd my-web-app
515
+ fastcar-cli init web
516
+ npm install
517
+ npm run debug
518
+
519
+ # RPC 项目
520
+ mkdir my-rpc-app && cd my-rpc-app
521
+ fastcar-cli init rpc
522
+ npm install
523
+ npm run debug
524
+
525
+ # Microservices 项目
526
+ mkdir my-ms-app && cd my-ms-app
527
+ fastcar-cli init microservices
528
+ npm install
529
+ npm run start-node
530
+ ```
531
+
532
+ ## 常见错误与注意事项
533
+
534
+ ### 1. 路由装饰器必须有括号
535
+
536
+ ❌ **错误:**
537
+ ```typescript
538
+ @GET
539
+ async list() { }
540
+ ```
541
+
542
+ ✅ **正确:**
543
+ ```typescript
544
+ @GET()
545
+ async list() { }
546
+ ```
547
+
548
+ ### 2. 不要使用不存在的装饰器
549
+
550
+ ❌ **错误:**
551
+ ```typescript
552
+ import { Body, Param, Query } from "@fastcar/koa/annotation";
553
+
554
+ @GET("/:id")
555
+ async getById(@Param("id") id: string) { }
556
+ ```
557
+
558
+ ✅ **正确:**
559
+ ```typescript
560
+ @GET("/:id")
561
+ async getById(id: string) { }
562
+ ```
563
+
564
+ ### 3. 表单验证使用 @ValidForm + @Rule
565
+
566
+ ❌ **错误:**
567
+ ```typescript
568
+ @POST()
569
+ async create(@Body body: ItemDTO) { }
570
+ ```
571
+
572
+ ✅ **正确:**
573
+ ```typescript
574
+ @ValidForm
575
+ @POST()
576
+ async create(@Rule() body: ItemDTO) { }
577
+ ```