@dangao/bun-server 1.1.2 → 1.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.
- package/docs/api.md +602 -0
- package/docs/best-practices.md +12 -0
- package/docs/custom-decorators.md +440 -0
- package/docs/deployment.md +447 -0
- package/docs/error-handling.md +462 -0
- package/docs/extensions.md +569 -0
- package/docs/guide.md +634 -0
- package/docs/migration.md +10 -0
- package/docs/performance.md +452 -0
- package/docs/troubleshooting.md +286 -0
- package/docs/zh/api.md +168 -0
- package/docs/zh/best-practices.md +38 -0
- package/docs/zh/custom-decorators.md +466 -0
- package/docs/zh/deployment.md +445 -0
- package/docs/zh/error-handling.md +456 -0
- package/docs/zh/extensions.md +584 -0
- package/docs/zh/guide.md +361 -0
- package/docs/zh/migration.md +86 -0
- package/docs/zh/performance.md +451 -0
- package/docs/zh/troubleshooting.md +279 -0
- package/package.json +4 -3
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
# 扩展系统
|
|
2
|
+
|
|
3
|
+
Bun Server Framework
|
|
4
|
+
提供了多种扩展方式,让你可以根据需求灵活地扩展应用功能。本文档介绍所有支持的扩展方式及其使用场景。
|
|
5
|
+
|
|
6
|
+
## 扩展方式概览
|
|
7
|
+
|
|
8
|
+
Bun Server 支持以下扩展方式:
|
|
9
|
+
|
|
10
|
+
1. **中间件(Middleware)** - 处理请求/响应流程
|
|
11
|
+
2. **应用扩展(Application Extension)** - 注册全局服务和功能
|
|
12
|
+
3. **模块(Module)** - 组织功能模块,支持导入导出
|
|
13
|
+
4. **自定义装饰器** - 扩展控制器和路由功能
|
|
14
|
+
|
|
15
|
+
## 1. 中间件(Middleware)
|
|
16
|
+
|
|
17
|
+
中间件是处理 HTTP 请求/响应流程的核心机制,可以在请求处理前后执行自定义逻辑。
|
|
18
|
+
|
|
19
|
+
### 全局中间件
|
|
20
|
+
|
|
21
|
+
通过 `app.use()` 注册全局中间件,所有请求都会经过这些中间件。
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
import {
|
|
25
|
+
Application,
|
|
26
|
+
createCorsMiddleware,
|
|
27
|
+
createLoggerMiddleware,
|
|
28
|
+
} from "@dangao/bun-server";
|
|
29
|
+
|
|
30
|
+
const app = new Application({ port: 3000 });
|
|
31
|
+
|
|
32
|
+
// 注册全局中间件
|
|
33
|
+
app.use(createLoggerMiddleware({ prefix: "[App]" }));
|
|
34
|
+
app.use(createCorsMiddleware({ origin: "*" }));
|
|
35
|
+
|
|
36
|
+
// 自定义中间件
|
|
37
|
+
app.use(async (ctx, next) => {
|
|
38
|
+
// 请求前处理
|
|
39
|
+
const start = Date.now();
|
|
40
|
+
|
|
41
|
+
// 调用下一个中间件或路由处理器
|
|
42
|
+
const response = await next();
|
|
43
|
+
|
|
44
|
+
// 请求后处理
|
|
45
|
+
const duration = Date.now() - start;
|
|
46
|
+
console.log(`Request took ${duration}ms`);
|
|
47
|
+
|
|
48
|
+
return response;
|
|
49
|
+
});
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### 控制器级中间件
|
|
53
|
+
|
|
54
|
+
使用 `@UseMiddleware()` 装饰器在控制器类或方法上应用中间件。
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
import { Controller, GET, UseMiddleware } from "@dangao/bun-server";
|
|
58
|
+
|
|
59
|
+
// 控制器级中间件
|
|
60
|
+
@Controller("/api")
|
|
61
|
+
@UseMiddleware(authMiddleware)
|
|
62
|
+
class ApiController {
|
|
63
|
+
@GET("/public")
|
|
64
|
+
public publicEndpoint() {
|
|
65
|
+
return { message: "Public data" };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// 方法级中间件
|
|
69
|
+
@GET("/admin")
|
|
70
|
+
@UseMiddleware(adminOnlyMiddleware)
|
|
71
|
+
public adminEndpoint() {
|
|
72
|
+
return { message: "Admin data" };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### 内置中间件
|
|
78
|
+
|
|
79
|
+
框架提供了多个内置中间件:
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
import {
|
|
83
|
+
createCorsMiddleware, // CORS 支持
|
|
84
|
+
createErrorHandlingMiddleware, // 错误处理
|
|
85
|
+
createFileUploadMiddleware, // 文件上传
|
|
86
|
+
createLoggerMiddleware, // 请求日志
|
|
87
|
+
createRequestLoggingMiddleware, // 详细请求日志
|
|
88
|
+
createStaticFileMiddleware, // 静态文件服务
|
|
89
|
+
} from "@dangao/bun-server";
|
|
90
|
+
|
|
91
|
+
app.use(createLoggerMiddleware({ prefix: "[App]" }));
|
|
92
|
+
app.use(createCorsMiddleware({ origin: "https://example.com" }));
|
|
93
|
+
app.use(createStaticFileMiddleware({ root: "./public", prefix: "/assets" }));
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### 推荐用法
|
|
97
|
+
|
|
98
|
+
- ✅ **全局中间件**:日志、错误处理、CORS、请求追踪
|
|
99
|
+
- ✅ **控制器级中间件**:认证、授权、限流
|
|
100
|
+
- ✅ **方法级中间件**:特定业务逻辑验证
|
|
101
|
+
|
|
102
|
+
## 2. 应用扩展(Application Extension)
|
|
103
|
+
|
|
104
|
+
应用扩展用于注册全局服务和功能,如日志系统、配置管理等。
|
|
105
|
+
|
|
106
|
+
### 使用扩展
|
|
107
|
+
|
|
108
|
+
```typescript
|
|
109
|
+
import {
|
|
110
|
+
Application,
|
|
111
|
+
LoggerExtension,
|
|
112
|
+
LogLevel,
|
|
113
|
+
SwaggerExtension,
|
|
114
|
+
} from "@dangao/bun-server";
|
|
115
|
+
|
|
116
|
+
const app = new Application({ port: 3000 });
|
|
117
|
+
|
|
118
|
+
// 注册 Logger 扩展
|
|
119
|
+
app.registerExtension(
|
|
120
|
+
new LoggerExtension({
|
|
121
|
+
prefix: "MyApp",
|
|
122
|
+
level: LogLevel.DEBUG,
|
|
123
|
+
}),
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
// 注册 Swagger 扩展
|
|
127
|
+
app.registerExtension(
|
|
128
|
+
new SwaggerExtension({
|
|
129
|
+
info: {
|
|
130
|
+
title: "My API",
|
|
131
|
+
version: "1.0.0",
|
|
132
|
+
},
|
|
133
|
+
servers: [{ url: "http://localhost:3000" }],
|
|
134
|
+
}),
|
|
135
|
+
);
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
### 创建自定义扩展
|
|
139
|
+
|
|
140
|
+
```typescript
|
|
141
|
+
import { Container } from "@dangao/bun-server";
|
|
142
|
+
import type { ApplicationExtension } from "@dangao/bun-server";
|
|
143
|
+
|
|
144
|
+
class MyExtension implements ApplicationExtension {
|
|
145
|
+
public register(container: Container): void {
|
|
146
|
+
// 注册服务到容器
|
|
147
|
+
container.registerInstance("MY_SERVICE", {
|
|
148
|
+
doSomething: () => console.log("Hello from extension"),
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
app.registerExtension(new MyExtension());
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### 推荐用法
|
|
157
|
+
|
|
158
|
+
- ✅ **全局服务注册**:日志、配置、数据库连接
|
|
159
|
+
- ✅ **功能模块初始化**:Swagger、监控、缓存
|
|
160
|
+
- ✅ **第三方集成**:认证服务、消息队列
|
|
161
|
+
|
|
162
|
+
## 3. 模块(Module)
|
|
163
|
+
|
|
164
|
+
模块系统提供了更结构化的方式来组织代码,支持依赖注入、服务导出和模块导入。
|
|
165
|
+
|
|
166
|
+
### 基础模块
|
|
167
|
+
|
|
168
|
+
```typescript
|
|
169
|
+
import { Controller, GET, Injectable, Module } from "@dangao/bun-server";
|
|
170
|
+
|
|
171
|
+
@Injectable()
|
|
172
|
+
class UserService {
|
|
173
|
+
public findAll() {
|
|
174
|
+
return [{ id: "1", name: "Alice" }];
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
@Controller("/api/users")
|
|
179
|
+
class UserController {
|
|
180
|
+
public constructor(private readonly userService: UserService) {}
|
|
181
|
+
|
|
182
|
+
@GET("/")
|
|
183
|
+
public list() {
|
|
184
|
+
return this.userService.findAll();
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
@Module({
|
|
189
|
+
controllers: [UserController],
|
|
190
|
+
providers: [UserService],
|
|
191
|
+
exports: [UserService], // 导出供其他模块使用
|
|
192
|
+
})
|
|
193
|
+
class UserModule {}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### 模块导入
|
|
197
|
+
|
|
198
|
+
```typescript
|
|
199
|
+
import { Module } from "@dangao/bun-server";
|
|
200
|
+
import { UserModule } from "./user.module";
|
|
201
|
+
import { OrderModule } from "./order.module";
|
|
202
|
+
|
|
203
|
+
@Module({
|
|
204
|
+
imports: [UserModule, OrderModule], // 导入其他模块
|
|
205
|
+
controllers: [AppController],
|
|
206
|
+
providers: [AppService],
|
|
207
|
+
})
|
|
208
|
+
class AppModule {}
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### 官方模块
|
|
212
|
+
|
|
213
|
+
框架提供了官方模块,可以通过 `imports` 引入:
|
|
214
|
+
|
|
215
|
+
#### LoggerModule
|
|
216
|
+
|
|
217
|
+
```typescript
|
|
218
|
+
import { LoggerModule, LogLevel, Module } from "@dangao/bun-server";
|
|
219
|
+
|
|
220
|
+
// 配置 Logger 模块
|
|
221
|
+
LoggerModule.forRoot({
|
|
222
|
+
logger: {
|
|
223
|
+
prefix: "MyApp",
|
|
224
|
+
level: LogLevel.DEBUG,
|
|
225
|
+
},
|
|
226
|
+
enableRequestLogging: true,
|
|
227
|
+
requestLoggingPrefix: "[MyApp]",
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
@Module({
|
|
231
|
+
imports: [LoggerModule], // 导入 Logger 模块
|
|
232
|
+
controllers: [UserController],
|
|
233
|
+
providers: [UserService],
|
|
234
|
+
})
|
|
235
|
+
class AppModule {}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
#### SwaggerModule
|
|
239
|
+
|
|
240
|
+
```typescript
|
|
241
|
+
import { Module, SwaggerModule } from "@dangao/bun-server";
|
|
242
|
+
|
|
243
|
+
// 配置 Swagger 模块
|
|
244
|
+
SwaggerModule.forRoot({
|
|
245
|
+
info: {
|
|
246
|
+
title: "My API",
|
|
247
|
+
version: "1.0.0",
|
|
248
|
+
description: "API documentation",
|
|
249
|
+
},
|
|
250
|
+
servers: [{ url: "http://localhost:3000" }],
|
|
251
|
+
uiPath: "/swagger",
|
|
252
|
+
jsonPath: "/swagger.json",
|
|
253
|
+
enableUI: true,
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
@Module({
|
|
257
|
+
imports: [SwaggerModule], // 导入 Swagger 模块
|
|
258
|
+
controllers: [UserController],
|
|
259
|
+
providers: [UserService],
|
|
260
|
+
})
|
|
261
|
+
class AppModule {}
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
#### SecurityModule(推荐)
|
|
265
|
+
|
|
266
|
+
SecurityModule 是统一的安全模块,参考 Spring Security
|
|
267
|
+
架构设计,支持多种认证方式:
|
|
268
|
+
|
|
269
|
+
```typescript
|
|
270
|
+
import { Auth, Module, SecurityModule } from "@dangao/bun-server";
|
|
271
|
+
|
|
272
|
+
// 配置安全模块
|
|
273
|
+
SecurityModule.forRoot({
|
|
274
|
+
jwt: {
|
|
275
|
+
secret: "your-secret-key",
|
|
276
|
+
accessTokenExpiresIn: 3600,
|
|
277
|
+
refreshTokenExpiresIn: 86400 * 7,
|
|
278
|
+
},
|
|
279
|
+
oauth2Clients: [
|
|
280
|
+
{
|
|
281
|
+
clientId: "my-client",
|
|
282
|
+
clientSecret: "my-secret",
|
|
283
|
+
redirectUris: ["http://localhost:3000/callback"],
|
|
284
|
+
grantTypes: ["authorization_code", "refresh_token"],
|
|
285
|
+
},
|
|
286
|
+
],
|
|
287
|
+
enableOAuth2Endpoints: true,
|
|
288
|
+
excludePaths: ["/api/public"],
|
|
289
|
+
defaultAuthRequired: false, // 默认不要求认证,通过 @Auth() 装饰器控制
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
@Module({
|
|
293
|
+
imports: [SecurityModule], // 导入安全模块
|
|
294
|
+
controllers: [UserController],
|
|
295
|
+
providers: [UserService],
|
|
296
|
+
})
|
|
297
|
+
class AppModule {}
|
|
298
|
+
|
|
299
|
+
// 使用 @Auth() 装饰器控制访问
|
|
300
|
+
@Controller("/api/users")
|
|
301
|
+
class UserController {
|
|
302
|
+
@GET("/me")
|
|
303
|
+
@Auth() // 需要认证
|
|
304
|
+
public getMe() {
|
|
305
|
+
return { user: "current user" };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
@GET("/admin")
|
|
309
|
+
@Auth({ roles: ["admin"] }) // 需要管理员角色
|
|
310
|
+
public getAdmin() {
|
|
311
|
+
return { message: "admin only" };
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
**SecurityModule 架构特点**:
|
|
317
|
+
|
|
318
|
+
- **核心抽象**:`AuthenticationManager` 管理认证流程
|
|
319
|
+
- **认证提供者**:支持多种认证方式(JWT、OAuth2 等)
|
|
320
|
+
- **访问决策**:`AccessDecisionManager` 处理授权决策
|
|
321
|
+
- **安全上下文**:`SecurityContext` 管理当前认证状态
|
|
322
|
+
- **可扩展**:可以自定义认证提供者和访问决策器
|
|
323
|
+
|
|
324
|
+
#### ConfigModule(配置管理)
|
|
325
|
+
|
|
326
|
+
ConfigModule 提供集中化的配置管理能力,并通过 `ConfigService` 提供类型安全的访问:
|
|
327
|
+
|
|
328
|
+
```typescript
|
|
329
|
+
import {
|
|
330
|
+
ConfigModule,
|
|
331
|
+
ConfigService,
|
|
332
|
+
CONFIG_SERVICE_TOKEN,
|
|
333
|
+
Module,
|
|
334
|
+
} from "@dangao/bun-server";
|
|
335
|
+
|
|
336
|
+
// 配置模块
|
|
337
|
+
ConfigModule.forRoot({
|
|
338
|
+
defaultConfig: {
|
|
339
|
+
app: {
|
|
340
|
+
port: Number(process.env.PORT ?? 3000),
|
|
341
|
+
name: "MyApp",
|
|
342
|
+
},
|
|
343
|
+
logger: {
|
|
344
|
+
prefix: "MyApp",
|
|
345
|
+
level: "debug",
|
|
346
|
+
},
|
|
347
|
+
},
|
|
348
|
+
load(env) {
|
|
349
|
+
// 从环境变量加载配置(可选)
|
|
350
|
+
return {
|
|
351
|
+
app: {
|
|
352
|
+
port: env.APP_PORT ? Number(env.APP_PORT) : undefined,
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
},
|
|
356
|
+
validate(config) {
|
|
357
|
+
if (!config.app?.name) {
|
|
358
|
+
throw new Error("app.name is required");
|
|
359
|
+
}
|
|
360
|
+
},
|
|
361
|
+
});
|
|
362
|
+
|
|
363
|
+
@Module({
|
|
364
|
+
imports: [ConfigModule],
|
|
365
|
+
controllers: [UserController],
|
|
366
|
+
})
|
|
367
|
+
class AppModule {}
|
|
368
|
+
|
|
369
|
+
// 在业务代码中注入 ConfigService
|
|
370
|
+
@Controller("/api")
|
|
371
|
+
class UserController {
|
|
372
|
+
public constructor(
|
|
373
|
+
@Inject(CONFIG_SERVICE_TOKEN)
|
|
374
|
+
private readonly config: ConfigService,
|
|
375
|
+
) {}
|
|
376
|
+
|
|
377
|
+
@GET("/info")
|
|
378
|
+
public info() {
|
|
379
|
+
const appName = this.config.get<string>("app.name", "MyApp");
|
|
380
|
+
const port = this.config.get<number>("app.port", 3000);
|
|
381
|
+
return { appName, port };
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
**ConfigModule 特点**:
|
|
387
|
+
|
|
388
|
+
- **集中配置来源**:支持默认配置 + 环境变量加载(`defaultConfig` + `load(env)`)
|
|
389
|
+
- **类型安全访问**:通过 `ConfigService.get/getRequired` 使用点号路径(如 `app.port`)
|
|
390
|
+
- **可验证**:`validate(config)` 钩子可集成 class-validator 风格校验
|
|
391
|
+
- **无侵入**:示例中(`basic-app.ts` / `full-app.ts` / `multi-module-app.ts` / `auth-app.ts`)均通过 `ConfigModule` 管理端口、日志前缀等配置
|
|
392
|
+
|
|
393
|
+
### 完整示例
|
|
394
|
+
|
|
395
|
+
```typescript
|
|
396
|
+
import {
|
|
397
|
+
Application,
|
|
398
|
+
Auth,
|
|
399
|
+
LoggerModule,
|
|
400
|
+
LogLevel,
|
|
401
|
+
Module,
|
|
402
|
+
SecurityModule,
|
|
403
|
+
SwaggerModule,
|
|
404
|
+
} from "@dangao/bun-server";
|
|
405
|
+
|
|
406
|
+
// 配置模块
|
|
407
|
+
LoggerModule.forRoot({
|
|
408
|
+
logger: { prefix: "App", level: LogLevel.INFO },
|
|
409
|
+
enableRequestLogging: true,
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
SwaggerModule.forRoot({
|
|
413
|
+
info: { title: "API", version: "1.0.0" },
|
|
414
|
+
uiPath: "/swagger",
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
SecurityModule.forRoot({
|
|
418
|
+
jwt: {
|
|
419
|
+
secret: "your-secret-key",
|
|
420
|
+
accessTokenExpiresIn: 3600,
|
|
421
|
+
},
|
|
422
|
+
oauth2Clients: [
|
|
423
|
+
{
|
|
424
|
+
clientId: "my-client",
|
|
425
|
+
clientSecret: "my-secret",
|
|
426
|
+
redirectUris: ["http://localhost:3000/callback"],
|
|
427
|
+
grantTypes: ["authorization_code"],
|
|
428
|
+
},
|
|
429
|
+
],
|
|
430
|
+
excludePaths: ["/api/public"],
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
// 应用模块
|
|
434
|
+
@Module({
|
|
435
|
+
imports: [LoggerModule, SwaggerModule, SecurityModule],
|
|
436
|
+
controllers: [UserController, OrderController],
|
|
437
|
+
providers: [UserService, OrderService],
|
|
438
|
+
})
|
|
439
|
+
class AppModule {}
|
|
440
|
+
|
|
441
|
+
// 注册模块
|
|
442
|
+
const app = new Application({ port: 3000 });
|
|
443
|
+
app.registerModule(AppModule);
|
|
444
|
+
app.listen();
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
### 推荐用法
|
|
448
|
+
|
|
449
|
+
- ✅ **业务模块化**:按领域拆分(UserModule、OrderModule)
|
|
450
|
+
- ✅ **功能模块**:使用官方模块(LoggerModule、SwaggerModule)
|
|
451
|
+
- ✅ **服务共享**:通过 `exports` 导出服务供其他模块使用
|
|
452
|
+
- ✅ **依赖管理**:通过 `imports` 管理模块依赖关系
|
|
453
|
+
|
|
454
|
+
## 4. 自定义装饰器
|
|
455
|
+
|
|
456
|
+
你可以创建自定义装饰器来扩展控制器和路由功能。
|
|
457
|
+
|
|
458
|
+
### 创建装饰器
|
|
459
|
+
|
|
460
|
+
```typescript
|
|
461
|
+
import "reflect-metadata";
|
|
462
|
+
|
|
463
|
+
// 缓存装饰器
|
|
464
|
+
export function Cache(ttl: number) {
|
|
465
|
+
return function (
|
|
466
|
+
target: any,
|
|
467
|
+
propertyKey: string,
|
|
468
|
+
descriptor: PropertyDescriptor,
|
|
469
|
+
) {
|
|
470
|
+
const originalMethod = descriptor.value;
|
|
471
|
+
const cache = new Map();
|
|
472
|
+
|
|
473
|
+
descriptor.value = async function (...args: any[]) {
|
|
474
|
+
const key = JSON.stringify(args);
|
|
475
|
+
if (cache.has(key)) {
|
|
476
|
+
return cache.get(key);
|
|
477
|
+
}
|
|
478
|
+
const result = await originalMethod.apply(this, args);
|
|
479
|
+
cache.set(key, result);
|
|
480
|
+
setTimeout(() => cache.delete(key), ttl);
|
|
481
|
+
return result;
|
|
482
|
+
};
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// 使用装饰器
|
|
487
|
+
@Controller("/api")
|
|
488
|
+
class ApiController {
|
|
489
|
+
@GET("/data")
|
|
490
|
+
@Cache(60000) // 缓存 60 秒
|
|
491
|
+
public getData() {
|
|
492
|
+
return { data: "expensive computation" };
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
### 推荐用法
|
|
498
|
+
|
|
499
|
+
- ✅ **横切关注点**:缓存、日志、性能监控
|
|
500
|
+
- ✅ **业务逻辑增强**:权限检查、数据转换
|
|
501
|
+
- ✅ **代码复用**:通用功能封装为装饰器
|
|
502
|
+
|
|
503
|
+
## 扩展方式对比
|
|
504
|
+
|
|
505
|
+
| 扩展方式 | 适用场景 | 优势 | 劣势 |
|
|
506
|
+
| ------------ | ------------------------ | ---------------------------- | ------------------ |
|
|
507
|
+
| **中间件** | 请求/响应处理流程 | 灵活、可组合、执行顺序可控 | 不适合注册全局服务 |
|
|
508
|
+
| **应用扩展** | 全局服务注册、功能初始化 | 统一管理、生命周期清晰 | 需要手动注册 |
|
|
509
|
+
| **模块** | 代码组织、依赖管理 | 结构化、可复用、支持导入导出 | 需要理解模块系统 |
|
|
510
|
+
| **装饰器** | 横切关注点、代码增强 | 声明式、易用 | 功能相对单一 |
|
|
511
|
+
|
|
512
|
+
## 推荐实践
|
|
513
|
+
|
|
514
|
+
### 1. 小型项目
|
|
515
|
+
|
|
516
|
+
使用中间件和扩展即可:
|
|
517
|
+
|
|
518
|
+
```typescript
|
|
519
|
+
const app = new Application({ port: 3000 });
|
|
520
|
+
|
|
521
|
+
// 注册扩展
|
|
522
|
+
app.registerExtension(new LoggerExtension());
|
|
523
|
+
app.registerExtension(new SwaggerExtension({...}));
|
|
524
|
+
|
|
525
|
+
// 注册中间件
|
|
526
|
+
app.use(createLoggerMiddleware());
|
|
527
|
+
app.use(createCorsMiddleware());
|
|
528
|
+
|
|
529
|
+
// 注册控制器
|
|
530
|
+
app.registerController(UserController);
|
|
531
|
+
```
|
|
532
|
+
|
|
533
|
+
### 2. 中型项目
|
|
534
|
+
|
|
535
|
+
使用模块系统组织代码:
|
|
536
|
+
|
|
537
|
+
```typescript
|
|
538
|
+
@Module({
|
|
539
|
+
imports: [LoggerModule, SwaggerModule],
|
|
540
|
+
controllers: [UserController, OrderController],
|
|
541
|
+
providers: [UserService, OrderService],
|
|
542
|
+
})
|
|
543
|
+
class AppModule {}
|
|
544
|
+
|
|
545
|
+
const app = new Application({ port: 3000 });
|
|
546
|
+
app.registerModule(AppModule);
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
### 3. 大型项目
|
|
550
|
+
|
|
551
|
+
按领域拆分模块,使用模块导入:
|
|
552
|
+
|
|
553
|
+
```typescript
|
|
554
|
+
// user.module.ts
|
|
555
|
+
@Module({
|
|
556
|
+
controllers: [UserController],
|
|
557
|
+
providers: [UserService],
|
|
558
|
+
exports: [UserService],
|
|
559
|
+
})
|
|
560
|
+
class UserModule {}
|
|
561
|
+
|
|
562
|
+
// order.module.ts
|
|
563
|
+
@Module({
|
|
564
|
+
imports: [UserModule], // 导入 UserModule 使用 UserService
|
|
565
|
+
controllers: [OrderController],
|
|
566
|
+
providers: [OrderService],
|
|
567
|
+
})
|
|
568
|
+
class OrderModule {}
|
|
569
|
+
|
|
570
|
+
// app.module.ts
|
|
571
|
+
@Module({
|
|
572
|
+
imports: [LoggerModule, SwaggerModule, UserModule, OrderModule],
|
|
573
|
+
})
|
|
574
|
+
class AppModule {}
|
|
575
|
+
```
|
|
576
|
+
|
|
577
|
+
## 总结
|
|
578
|
+
|
|
579
|
+
- **中间件**:处理请求/响应流程,适合日志、认证、错误处理
|
|
580
|
+
- **应用扩展**:注册全局服务,适合日志系统、配置管理
|
|
581
|
+
- **模块**:组织代码结构,适合业务模块化和依赖管理
|
|
582
|
+
- **装饰器**:增强代码功能,适合横切关注点
|
|
583
|
+
|
|
584
|
+
根据项目规模和需求,选择合适的扩展方式,或组合使用多种方式。
|