@fastcar/cli 0.1.2 → 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,856 +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, (7) Selecting and configuring project templates (web, rpc, cos, static, microservices), (8) Writing application.yml for different templates.
4
- ---
5
-
6
- # FastCar Framework
7
-
8
- FastCar 是基于 TypeScript 的 Node.js 企业级应用开发框架,灵感来源于 Spring Boot,采用 IoC(控制反转)设计思想。
9
-
10
- ## 核心概念
11
-
12
- ### IoC 容器与装饰器
13
-
14
- | 装饰器 | 用途 | 示例 |
15
- |--------|------|------|
16
- | `@Application` | 入口应用类 | `@Application class App {}` |
17
- | `@Component` | 通用组件 | `@Component class UtilService {}` |
18
- | `@Service` | 服务层 | `@Service class UserService {}` |
19
- | `@Controller` | 控制器层 | `@Controller class UserController {}` |
20
- | `@Repository` | 数据访问层 | `@Repository class UserRepository {}` |
21
- | `@Autowired` | 依赖注入 | `@Autowired private userService!: UserService;` |
22
-
23
- ### 基础应用结构
24
-
25
- ```typescript
26
- import { FastCarApplication } from "@fastcar/core";
27
- import { Application, Autowired, Component, Service } from "@fastcar/core/annotation";
28
-
29
- // 服务层
30
- @Service
31
- class UserService {
32
- getUsers() {
33
- return [{ id: 1, name: "Alice" }];
34
- }
35
- }
36
-
37
- // 控制器层
38
- @Controller
39
- class UserController {
40
- @Autowired
41
- private userService!: UserService;
42
-
43
- getUsers() {
44
- return this.userService.getUsers();
45
- }
46
- }
47
-
48
- // 应用入口
49
- @Application
50
- class App {
51
- app!: FastCarApplication;
52
-
53
- async start() {
54
- console.log("应用启动成功!");
55
- }
56
- }
57
-
58
- // 启动
59
- const app = new App();
60
- app.start();
61
- ```
62
-
63
- ## 模块速查
64
-
65
- ### Web 开发 (@fastcar/koa)
66
-
67
- **正确的路由装饰器使用方式:**
68
-
69
- ```typescript
70
- import { GET, POST, REQUEST } from "@fastcar/koa/annotation";
71
-
72
- @Controller
73
- @REQUEST("/api/users")
74
- class UserController {
75
- // GET 请求 - 无路径参数时必须有括号
76
- @GET()
77
- async list() {
78
- return { data: [] };
79
- }
80
-
81
- // GET 请求 - 有路径参数
82
- @GET("/:id")
83
- async getById(id: string) {
84
- return { id };
85
- }
86
-
87
- // POST 请求
88
- @POST()
89
- async create(body: UserDTO) {
90
- return { created: true };
91
- }
92
- }
93
- ```
94
-
95
- **⚠️ 重要:FastCar 没有 `@Body`, `@Param`, `@Query` 装饰器**
96
-
97
- - 请求参数直接作为方法参数传入
98
- - GET 请求参数通过方法参数直接获取
99
- - POST 请求体通过 `body` 参数获取
100
- - 路径参数通过方法参数直接获取
101
-
102
- ### 数据库 (@fastcar/mysql)
103
-
104
- **实体定义:**
105
-
106
- ```typescript
107
- import { Table, Field, DBType, PrimaryKey, NotNull, Size } from "@fastcar/core/annotation";
108
-
109
- @Table("users")
110
- class User {
111
- @Field("id")
112
- @DBType("int")
113
- @PrimaryKey
114
- id!: number;
115
-
116
- @Field("name")
117
- @DBType("varchar")
118
- @NotNull
119
- @Size({ maxSize: 50 })
120
- name!: string;
121
- }
122
- ```
123
-
124
- **Mapper 定义:**
125
-
126
- ```typescript
127
- import { Entity, Repository } from "@fastcar/core/annotation";
128
- import { MysqlMapper } from "@fastcar/mysql";
129
-
130
- @Entity(User)
131
- @Repository
132
- class UserMapper extends MysqlMapper<User> {}
133
-
134
- export default UserMapper;
135
- ```
136
-
137
- **Service 中使用:**
138
-
139
- ```typescript
140
- import { Service, Autowired } from "@fastcar/core/annotation";
141
- import { OrderEnum } from "@fastcar/core/db";
142
- import UserMapper from "./UserMapper";
143
-
144
- @Service
145
- class UserService {
146
- @Autowired
147
- private userMapper!: UserMapper;
148
-
149
- // 查询列表
150
- async getUsers() {
151
- return this.userMapper.select({
152
- where: { status: 1 },
153
- orders: { createTime: OrderEnum.desc },
154
- limit: 10
155
- });
156
- }
157
-
158
- // 查询单个
159
- async getUser(id: number) {
160
- return this.userMapper.selectOne({ where: { id } });
161
- }
162
-
163
- // 根据主键查询
164
- async getUserById(id: number) {
165
- return this.userMapper.selectByPrimaryKey({ id } as User);
166
- }
167
-
168
- // 插入
169
- async createUser(user: User) {
170
- return this.userMapper.saveOne(user);
171
- }
172
-
173
- // 更新
174
- async updateUser(id: number, data: Partial<User>) {
175
- return this.userMapper.update({ where: { id }, row: data });
176
- }
177
-
178
- // 根据主键更新
179
- async updateById(user: User) {
180
- return this.userMapper.updateByPrimaryKey(user);
181
- }
182
-
183
- // 删除
184
- async deleteUser(id: number) {
185
- return this.userMapper.delete({ where: { id } });
186
- }
187
-
188
- // 统计
189
- async count() {
190
- return this.userMapper.count({});
191
- }
192
- }
193
- ```
194
-
195
- ### 表单验证 (@fastcar/core)
196
-
197
- **正确的表单验证方式:**
198
-
199
- ```typescript
200
- import { ValidForm, NotNull, Size, Rule } from "@fastcar/core/annotation";
201
-
202
- // DTO 类定义在单独的文件中,如 dto/UserDTO.ts
203
- class UserDTO {
204
- @NotNull
205
- name!: string;
206
-
207
- @Size({ minSize: 1, maxSize: 150 })
208
- age!: number;
209
- }
210
-
211
- @Controller
212
- @REQUEST("/api/users")
213
- class UserController {
214
-
215
- // GET 请求 - 无需表单验证
216
- @GET()
217
- async list(page: number = 1, pageSize: number = 10) {
218
- return { page, pageSize, data: [] };
219
- }
220
-
221
- // POST 请求 - 使用 @ValidForm + @Rule 进行表单验证
222
- @ValidForm
223
- @POST()
224
- async create(@Rule() body: UserDTO) {
225
- // 参数会自动校验,如果校验失败会抛出异常
226
- const { name, age } = body;
227
- return this.userService.create({ name, age });
228
- }
229
- }
230
- ```
231
-
232
- **表单验证规则:**
233
-
234
- | 装饰器 | 用途 | 示例 |
235
- |--------|------|------|
236
- | `@ValidForm` | 开启方法参数校验 | 放在方法上 |
237
- | `@Rule()` | 标记校验对象 | 放在 DTO 参数前 |
238
- | `@NotNull` | 参数不能为空 | 放在 DTO 字段上 |
239
- | `@Size({min, max})` | 大小限制 | 放在 DTO 字段上 |
240
-
241
- **⚠️ 常见错误:**
242
-
243
- ❌ **错误** - 使用不存在的装饰器:
244
- ```typescript
245
- // 这些装饰器在 FastCar 中不存在!
246
- import { Body, Param, Query } from "@fastcar/koa/annotation"; // 错误
247
-
248
- @GET("/:id")
249
- async getById(@Param("id") id: string) { ... } // ❌ 错误
250
-
251
- @POST()
252
- async create(@Body body: UserDTO) { ... } // ❌ 错误
253
- ```
254
-
255
- ✅ **正确** - 直接使用方法参数:
256
- ```typescript
257
- @GET("/:id")
258
- async getById(id: string) { ... } // ✅ 正确
259
-
260
- @POST()
261
- async create(body: UserDTO) { ... } // ✅ 正确
262
-
263
- @GET()
264
- async list(page: number = 1) { ... } // ✅ 正确
265
- ```
266
-
267
- ### Redis (@fastcar/redis)
268
-
269
- ```typescript
270
- import { Service, Autowired } from "@fastcar/core/annotation";
271
- import { RedisClient } from "@fastcar/redis/annotation";
272
-
273
- @Service
274
- class CacheService {
275
- @RedisClient
276
- private redis!: RedisClient;
277
-
278
- async get(key: string) {
279
- return this.redis.get(key);
280
- }
281
-
282
- async set(key: string, value: string, ttl?: number) {
283
- await this.redis.set(key, value, ttl);
284
- }
285
- }
286
- ```
287
-
288
- ### 定时任务 (@fastcar/timer)
289
-
290
- ```typescript
291
- import { Scheduled, Cron } from "@fastcar/timer/annotation";
292
-
293
- @Component
294
- class TaskService {
295
- // 间隔执行(毫秒)
296
- @Scheduled(60000)
297
- async intervalTask() {
298
- console.log("每分钟执行");
299
- }
300
-
301
- // Cron 表达式
302
- @Cron("0 0 * * * *")
303
- async hourlyTask() {
304
- console.log("每小时执行");
305
- }
306
- }
307
- ```
308
-
309
- ### 工作线程池 (@fastcar/workerpool)
310
-
311
- ```typescript
312
- import { WorkerPool, WorkerTask } from "@fastcar/workerpool/annotation";
313
-
314
- @Component
315
- class ComputeService {
316
- @WorkerPool({ minWorkers: 2, maxWorkers: 4 })
317
- private pool!: WorkerPool;
318
-
319
- @WorkerTask
320
- heavyComputation(data: number[]): number {
321
- // worker 线程中执行
322
- return data.reduce((a, b) => a + b, 0);
323
- }
324
- }
325
- ```
326
-
327
- ## 项目模板速查
328
-
329
- FastCar CLI 提供 5 种项目模板,分别适用于不同的业务场景。
330
-
331
- ### 模板选择指南
332
-
333
- | 模板 | 适用场景 | 核心依赖 | 关键注解 |
334
- |------|---------|---------|---------|
335
- | web | RESTful API 服务 | @fastcar/koa, @fastcar/server | @EnableKoa |
336
- | static | 静态资源服务器 | @fastcar/koa, @fastcar/server | @EnableKoa + KoaStatic |
337
- | rpc | RPC 微服务通信 | @fastcar/rpc, @fastcar/server | @EnableRPC |
338
- | cos | 对象存储/文件上传/直播转码 | @fastcar/koa, @fastcar/cossdk, @fastcar/server | @EnableKoa |
339
- | microservices | 分布式多服务架构 | @fastcar/koa, @fastcar/rpc, @fastcar/server, @fastcar/timer | @EnableKoa / @EnableRPC(按服务模块) |
340
-
341
- ### 各模板入口示例
342
-
343
- #### Web 模板
344
- ```typescript
345
- import { FastCarApplication } from "@fastcar/core";
346
- import { Application } from "@fastcar/core/annotation";
347
- import { EnableKoa, KoaMiddleware } from "@fastcar/koa/annotation";
348
- import { ExceptionGlobalHandler, KoaBodyParser } from "@fastcar/koa";
349
-
350
- @Application
351
- @EnableKoa
352
- @KoaMiddleware(ExceptionGlobalHandler)
353
- @KoaMiddleware(KoaBodyParser)
354
- class APP {
355
- app!: FastCarApplication;
356
- }
357
- export default new APP();
358
- ```
359
-
360
- #### Static 模板
361
- ```typescript
362
- import { Application } from "@fastcar/core/annotation";
363
- import { EnableKoa, KoaMiddleware } from "@fastcar/koa/annotation";
364
- import { ExceptionGlobalHandler, KoaStatic } from "@fastcar/koa";
365
-
366
- @Application
367
- @EnableKoa
368
- @KoaMiddleware(ExceptionGlobalHandler)
369
- @KoaMiddleware(KoaStatic)
370
- class APP {
371
- app!: any;
372
- }
373
- export default new APP();
374
- ```
375
-
376
- #### RPC 模板
377
- ```typescript
378
- import { Application } from "@fastcar/core/annotation";
379
- import { EnableRPC } from "@fastcar/rpc/annotation";
380
-
381
- @Application
382
- @EnableRPC
383
- class APP {}
384
- export default new APP();
385
- ```
386
-
387
- #### COS 模板
388
- ```typescript
389
- import { Application } from "@fastcar/core/annotation";
390
- import { EnableKoa, KoaMiddleware } from "@fastcar/koa/annotation";
391
- import { ExceptionGlobalHandler, KoaBody, KoaBodyParser, KoaCors } from "@fastcar/koa";
392
-
393
- @EnableKoa
394
- @Application
395
- @KoaMiddleware(ExceptionGlobalHandler, KoaBody, KoaBodyParser, KoaCors)
396
- class APP {}
397
- export default new APP();
398
- ```
399
-
400
- #### Microservices 模板
401
- 微服务模板采用多服务架构,包含 `app-node.ts`(子进程启动多服务)和 `app-pm2.ts`(PM2 启动入口)。服务模块分为:
402
- - **center**:服务中心,提供服务注册与发现
403
- - **connector**:连接器服务,处理客户端连接
404
- - **chat**:聊天服务,处理实时消息
405
- - **web**:Web 服务,提供 HTTP 接口
406
- - **base**:基础服务,提供公共功能
407
-
408
- 各服务模块内部根据职责使用 `@EnableKoa` 或 `@EnableRPC`。
409
-
410
- ### 项目结构示例
411
-
412
- **Web / Static / RPC / COS 模板**
413
- ```
414
- template/
415
- ├── src/
416
- │ ├── controller/ # 控制器(web/cos)
417
- │ ├── dto/ # DTO 类(表单验证)
418
- │ ├── middleware/ # 中间件(web/cos)
419
- │ ├── model/ # 数据模型
420
- │ └── app.ts # 应用入口
421
- ├── resource/
422
- │ └── application.yml # 配置文件
423
- ├── target/ # 编译输出
424
- ├── package.json
425
- ├── tsconfig.json
426
- └── ecosystem.config.yml
427
- ```
428
-
429
- **Microservices 模板**
430
- ```
431
- template/
432
- ├── src/
433
- │ ├── annotation/ # 注解定义
434
- │ ├── common/ # 公共代码
435
- │ ├── middleware/ # 中间件
436
- │ ├── servers/ # 服务目录
437
- │ │ ├── base/ # 基础服务
438
- │ │ ├── center/ # 服务中心
439
- │ │ ├── chat/ # 聊天服务
440
- │ │ ├── connector/ # 连接器服务
441
- │ │ └── web/ # Web 服务
442
- │ ├── types/ # 类型定义
443
- │ ├── utils/ # 工具函数
444
- │ ├── app-node.ts # 单节点入口(子进程启动)
445
- │ └── app-pm2.ts # PM2 入口
446
- ├── resource/
447
- │ ├── application.yml
448
- │ ├── application-dev.yml
449
- │ └── ecosystem.config.yml
450
- ├── test/
451
- ├── package.json
452
- └── tsconfig.json
453
- ```
454
-
455
- ### 模板依赖安装
456
-
457
- ```bash
458
- # Web / Static
459
- npm i @fastcar/core @fastcar/koa @fastcar/server
460
-
461
- # RPC
462
- npm i @fastcar/core @fastcar/rpc @fastcar/server
463
-
464
- # COS
465
- npm i @fastcar/core @fastcar/koa @fastcar/cossdk @fastcar/server
466
-
467
- # Microservices
468
- npm i @fastcar/core @fastcar/koa @fastcar/rpc @fastcar/server @fastcar/timer
469
- ```
470
-
471
- ## 配置管理
472
-
473
- 配置文件放在 `resource/application.yml`。FastCar 支持按 `env` 加载多文件,例如 `application-dev.yml` 会与主配置合并。
474
-
475
- ### 基础配置示例
476
-
477
- ```yaml
478
- application:
479
- name: my-app
480
- version: 1.0.0
481
- env: dev
482
-
483
- mysql:
484
- host: localhost
485
- port: 3306
486
- database: mydb
487
- username: root
488
- password: password
489
-
490
- redis:
491
- host: localhost
492
- port: 6379
493
- ```
494
-
495
- 使用配置:
496
-
497
- ```typescript
498
- import { Configure, Value } from "@fastcar/core/annotation";
499
-
500
- @Configure
501
- class AppConfig {
502
- @Value("server.port")
503
- port!: number;
504
-
505
- @Value("mysql.host")
506
- dbHost!: string;
507
- }
508
- ```
509
-
510
- ### 各模板 application.yml 详解
511
-
512
- #### Web / Static / COS 通用 Koa 配置
513
-
514
- ```yaml
515
- application:
516
- env: "dev"
517
-
518
- settings:
519
- koa:
520
- server:
521
- - { port: 8080, host: "0.0.0.0" }
522
- # HTTPS 示例:
523
- # - { port: 443, host: "0.0.0.0", protocol: https, ssl: { key: "./ssl/server.key", cert: "./ssl/server.pem" } }
524
- koaStatic: # 静态资源映射
525
- { "public": "public" } # 别名: 路径(相对 resource 目录或绝对路径)
526
- koaBodyParser: # 请求体解析
527
- enableTypes: ["json", "form", "text"]
528
- extendTypes: { text: ["text/xml", "application/xml"] }
529
- ```
530
-
531
- - `settings.koa.server`:服务器监听配置数组。支持 `http`(默认)、`http2`、`https`;启用 HTTPS 时需额外指定 `protocol: https` 和 `ssl.key / ssl.cert`。
532
- - `settings.koa.koaStatic`:静态资源访问映射,格式为 `{ "别名": "路径" }`。
533
- - `settings.koa.koaBodyParser`:Koa Body 解析器配置,`enableTypes` 控制允许的请求体类型,`extendTypes` 可扩展 XML 等特殊类型。
534
-
535
- #### RPC 模板配置
536
-
537
- ```yaml
538
- application:
539
- name: "fastcar-boot-rpc"
540
-
541
- settings:
542
- rpc:
543
- list:
544
- - id: "server-1"
545
- type: "ws" # 通信协议:ws / http / grpc / mqtt
546
- server: { port: 1235 }
547
- extra: {}
548
- serviceType: "base" # 服务类型分类
549
- secure:
550
- username: "user"
551
- password: "123456"
552
- ```
553
-
554
- - `settings.rpc.list`:RPC 服务端点数组。
555
- - `id`:节点唯一标识。
556
- - `type`:通信协议,常见取值 `ws`、`http`、`grpc`、`mqtt`。
557
- - `server`:监听配置,通常只写 `{ port }`。
558
- - `extra`:协议扩展参数。
559
- - `serviceType`:服务类型,用于服务分组或路由。
560
- - `secure`:安全认证信息,包含 `username` 和 `password`。
561
-
562
- #### COS 模板特有配置
563
-
564
- ```yaml
565
- application:
566
- env: "prod"
567
-
568
- settings:
569
- hotterSysConfig: true # 启用系统配置热更新监听
570
- ```
571
-
572
- - `settings.hotterSysConfig`:设为 `true` 时,框架会监听配置变更并自动热更新。
573
-
574
- #### Microservices 模板配置
575
-
576
- 主配置通常只声明环境:
577
-
578
- ```yaml
579
- application:
580
- env: "dev"
581
- ```
582
-
583
- 详细集群配置放在 `application-dev.yml`:
584
-
585
- ```yaml
586
- settings:
587
- hotterSysConfig: true # 监听系统配置变更
588
-
589
- microservices:
590
- center: # 服务中心
591
- token: "nW0tT4bZ6qM7mF7wD2rT2pR9dT7gK3hZ"
592
- servers:
593
- - host: "localhost"
594
- clusters: 1 # 实例数,serviceId 和端口号自动递增
595
- list:
596
- - type: "ws"
597
- server: { port: 60000 }
598
- timeout: 0 # 0 表示永不超时
599
- connectionLimit: 1
600
- disconnectInterval: 1000 # 断线重连间隔(毫秒)
601
- retry:
602
- retryCount: 3
603
- retryInterval: 3000
604
- timeout: 30000
605
- maxMsgNum: 10000
606
- increase: true
607
-
608
- connector: # 连接器服务
609
- token: "x3TGsWC9uloZu235LA07eAiJ61nQ1A5f"
610
- servers:
611
- - host: "localhost"
612
- clusters: 1
613
- list:
614
- - front: true # 标记为面向客户端的前置节点
615
- type: "ws"
616
- server: { port: 60100 }
617
-
618
- chat: # 聊天服务
619
- token: "go0kbkNM3wQ4e2Vgo0kbkNM3wQ4e2V"
620
- servers:
621
- - host: "localhost"
622
- clusters: 1
623
- list:
624
- - type: "ws"
625
- server: { port: 60200 }
626
-
627
- web: # Web 服务
628
- token: "go0kbkNM3wQ4e2Vgo0kbkNM3wQ4e2V"
629
- koa:
630
- koaBodyParser:
631
- enableTypes: ["json", "form", "text"]
632
- extendTypes: { text: ["text/xml", "application/xml"] }
633
- servers:
634
- - host: "localhost"
635
- clusters: 1
636
- list:
637
- - type: "http"
638
- server: { port: 8080 }
639
- - type: "ws"
640
- server: { port: 60300 }
641
- ```
642
-
643
- - `settings.microservices.<服务名>`:定义各微服务模块的集群配置。
644
- - `token`:服务间通信鉴权令牌,防止非法节点接入。
645
- - `servers`:服务器集群列表。
646
- - `host`:主机地址。
647
- - `clusters`:集群实例数量。若大于 1,框架会自动递增 `serviceId` 和端口号生成多个实例。
648
- - `list`:该集群对外暴露的协议端点列表。
649
- - `type`:协议类型,如 `ws`、`http`。
650
- - `server`:端口配置 `{ port }`。
651
- - `front: true`:仅 connector 等前置服务需要,表示该节点直接面向客户端。
652
- - `timeout`:连接超时时间(毫秒),`0` 表示永不超时。
653
- - `connectionLimit`:最大连接数限制。
654
- - `disconnectInterval`:断线后重连间隔(毫秒)。
655
- - `retry`:消息重试策略。
656
- - `retryCount`:最大重试次数。
657
- - `retryInterval`:重试间隔。
658
- - `timeout`:重试总超时。
659
- - `maxMsgNum`:消息队列最大长度。
660
- - `increase`:是否递增重试间隔。
661
-
662
- ## 生命周期钩子
663
-
664
- ```typescript
665
- import { ApplicationStart, ApplicationStop, ApplicationInit } from "@fastcar/core/annotation";
666
-
667
- @Component
668
- class LifecycleService {
669
- // 应用启动时执行
670
- @ApplicationStart
671
- async onStart() {
672
- console.log("应用启动");
673
- }
674
-
675
- // 应用停止前执行
676
- @ApplicationStop
677
- async onStop() {
678
- console.log("应用停止");
679
- }
680
-
681
- // 初始化(配合 @ApplicationRunner)
682
- @ApplicationInit
683
- async init() {
684
- console.log("初始化完成");
685
- }
686
- }
687
- ```
688
-
689
- ## 工具类
690
-
691
- ```typescript
692
- import { DateUtil, CryptoUtil, FileUtil, TypeUtil } from "@fastcar/core/utils";
693
-
694
- // 日期时间
695
- DateUtil.toDateTime(); // "2024-03-10 15:30:45"
696
- DateUtil.toDay(); // "2024-03-10"
697
-
698
- // 加密
699
- CryptoUtil.aesEncode(key, iv, "data");
700
- CryptoUtil.sha256Encode("password");
701
-
702
- // 文件操作
703
- FileUtil.getFilePathList("./src");
704
- FileUtil.getResource("./config.yml");
705
-
706
- // 类型判断
707
- TypeUtil.isFunction(() => {}); // true
708
- TypeUtil.isClass(MyClass); // true
709
- ```
710
-
711
- ## 完整模块列表
712
-
713
- | 模块 | 安装命令 | 用途 |
714
- |------|----------|------|
715
- | @fastcar/core | `npm i @fastcar/core` | IoC 容器、配置管理 |
716
- | @fastcar/koa | `npm i @fastcar/koa @fastcar/server` | Web 开发 |
717
- | @fastcar/mysql | `npm i @fastcar/mysql` | MySQL 数据库 |
718
- | @fastcar/pgsql | `npm i @fastcar/pgsql` | PostgreSQL |
719
- | @fastcar/mongo | `npm i @fastcar/mongo` | MongoDB |
720
- | @fastcar/redis | `npm i @fastcar/redis` | Redis 缓存 |
721
- | @fastcar/cache | `npm i @fastcar/cache` | 缓存组件 |
722
- | @fastcar/timer | `npm i @fastcar/timer` | 定时任务 |
723
- | @fastcar/timewheel | `npm i @fastcar/timewheel` | 时间轮延时任务 |
724
- | @fastcar/workerpool | `npm i @fastcar/workerpool` | 工作线程池 |
725
- | @fastcar/rpc | `npm i @fastcar/rpc` | RPC 通信 |
726
- | @fastcar/serverless | `npm i @fastcar/serverless` | Serverless 支持 |
727
- | @fastcar/cos-sdk | `npm i @fastcar/cos-sdk` | 对象存储 |
728
-
729
- ## 快速开始新项目
730
-
731
- ### 使用 CLI 创建项目(推荐)
732
-
733
- ```bash
734
- # Web 项目
735
- mkdir my-web-app && cd my-web-app
736
- fastcar-cli init web
737
- npm install
738
- npm run debug
739
-
740
- # Static 项目
741
- mkdir my-static-app && cd my-static-app
742
- fastcar-cli init static
743
- npm install
744
- npm run debug
745
-
746
- # RPC 项目
747
- mkdir my-rpc-app && cd my-rpc-app
748
- fastcar-cli init rpc
749
- npm install
750
- npm run debug
751
-
752
- # COS 项目
753
- mkdir my-cos-app && cd my-cos-app
754
- fastcar-cli init cos
755
- npm install
756
- npm run debug
757
-
758
- # Microservices 项目
759
- mkdir my-ms-app && cd my-ms-app
760
- fastcar-cli init microservices
761
- npm install
762
- npm run start-node # 单节点模式(子进程启动全部服务)
763
- # 或
764
- npm run start-pm2 # PM2 模式
765
- ```
766
-
767
- ### 手动创建项目
768
-
769
- ```bash
770
- # 1. 创建项目
771
- mkdir my-fastcar-app && cd my-fastcar-app
772
- npm init -y
773
-
774
- # 2. 安装依赖
775
- npm i @fastcar/core @fastcar/koa @fastcar/server
776
- npm i -D typescript ts-node @types/node
777
-
778
- # 3. 初始化 TypeScript
779
- npx tsc --init
780
-
781
- # 4. 启用装饰器(tsconfig.json)
782
- # "experimentalDecorators": true
783
- # "emitDecoratorMetadata": true
784
-
785
- # 5. 创建入口文件和配置文件,开始开发
786
- ```
787
-
788
- ## 常见错误与注意事项
789
-
790
- ### 1. 路由装饰器必须有括号
791
-
792
- ❌ **错误:**
793
- ```typescript
794
- @GET
795
- async list() { }
796
- ```
797
-
798
- ✅ **正确:**
799
- ```typescript
800
- @GET()
801
- async list() { }
802
- ```
803
-
804
- ### 2. 不要使用不存在的装饰器
805
-
806
- ❌ **错误:**
807
- ```typescript
808
- import { Body, Param, Query } from "@fastcar/koa/annotation";
809
-
810
- @GET("/:id")
811
- async getById(@Param("id") id: string) { }
812
-
813
- @POST()
814
- async create(@Body body: UserDTO) { }
815
- ```
816
-
817
- ✅ **正确:**
818
- ```typescript
819
- @GET("/:id")
820
- async getById(id: string) { }
821
-
822
- @POST()
823
- async create(body: UserDTO) { }
824
- ```
825
-
826
- ### 3. 表单验证使用 @ValidForm + @Rule
827
-
828
- ❌ **错误:**
829
- ```typescript
830
- @POST()
831
- async create(@Body body: UserDTO) { }
832
- ```
833
-
834
- ✅ **正确:**
835
- ```typescript
836
- @ValidForm
837
- @POST()
838
- async create(@Rule() body: UserDTO) { }
839
- ```
840
-
841
- ### 4. DTO 类放在单独文件夹
842
-
843
- 推荐项目结构:
844
- ```
845
- src/
846
- ├── controller/ # 控制器
847
- ├── dto/ # DTO 类(表单验证)
848
- ├── service/ # 服务层
849
- ├── model/ # 数据模型
850
- └── app.ts
851
- ```
852
-
853
- ## 参考资源
854
-
855
- - 详细 API 文档:[references/api-reference.md](references/api-reference.md)
856
- - 项目模板:[assets/project-template/](assets/project-template/)
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
+ ```