Skip to content

系列回顾 📚 ​

在这个 NestJS 深入浅出系列中,我们已经详细探讨了以下主题:

  1. 框架介绍与项目搭建 🏗️

    • 框架特点和优势
    • 项目初始化和结构
    • 基本概念介绍
  2. 控制器(Controller) 🎮

    • 路由处理
    • 请求参数处理
    • 响应处理
    • 路由装饰器
  3. 提供者(Provider) 💉

    • 依赖注入系统
    • 服务的创建和使用
    • 作用域和生命周期
    • 自定义提供者
  4. 模块(Module) 📦

    • 模块组织
    • 依赖管理
    • 动态模块
    • 共享模块
  5. 中间件(Middleware) ⛓️

    • 请求处理流程
    • 全局中间件
    • 路由中间件
    • 函数式中间件
  6. 装饰器(Decorator) 🎨

    • 内置装饰器
    • 自定义装饰器
    • 参数装饰器
    • 方法装饰器
  7. 管道(Pipe) 🚰

    • 数据转换
    • 数据验证
    • 内置管道
    • 自定义管道
  8. 守卫(Guard) 🛡️

    • 认证授权
    • 角色控制
    • 权限管理
    • 访问控制
  9. 拦截器(Interceptor) 🎯

    • 响应转换
    • 异常处理
    • 缓存处理
    • 日志记录
  10. 异常过滤器(Exception Filter) 🚨

    • 错误处理
    • 异常捕获
    • 错误响应
    • 日志记录
  11. 配置系统(Configuration) ⚙️

    • 环境配置
    • 配置验证
    • 动态配置
    • 敏感信息处理

核心概念关系图 🗺️ ​

mermaid
graph TD
    A[客户端请求] --> B[中间件]
    B --> C[守卫]
    C --> D[拦截器 Before]
    D --> E[管道]
    E --> F[控制器]
    F --> G[服务]
    G --> H[拦截器 After]
    H --> I[异常过滤器]
    I --> J[响应]

最佳实践总结 💡 ​

1. 项目结构组织 ​

src/
├── modules/           # 功能模块
│   ├── users/
│   ├── auth/
│   └── products/
├── common/            # 公共功能
│   ├── decorators/
│   ├── filters/
│   ├── guards/
│   ├── interceptors/
│   └── pipes/
├── config/           # 配置文件
├── interfaces/       # 类型定义
└── main.ts          # 应用入口

2. 依赖注入最佳实践 ​

typescript
// 使用接口和令牌
export interface IUserService {
  findOne(id: string): Promise<User>;
  create(data: CreateUserDto): Promise<User>;
}

export const USER_SERVICE = 'USER_SERVICE';

@Injectable()
export class UserService implements IUserService {
  // 实现接口方法
}

// 在模块中提供
{
  provide: USER_SERVICE,
  useClass: UserService
}

3. 错误处理策略 ​

typescript
// 统一的错误响应格式
export interface ErrorResponse {
  code: string;
  message: string;
  timestamp: string;
  path: string;
  details?: any;
}

// 业务错误代码管理
export const ErrorCodes = {
  VALIDATION_ERROR: 'E0001',
  UNAUTHORIZED: 'E0002',
  FORBIDDEN: 'E0003',
  // ...
} as const;

4. 安全最佳实践 ​

typescript
// 1. 使用环境变量
@Injectable()
export class ConfigService {
  private readonly envConfig: EnvConfig;

  constructor() {
    const result = validateEnv(process.env);
    this.envConfig = result;
  }
}

// 2. 密码加密
@Injectable()
export class AuthService {
  async validateUser(password: string, hashedPassword: string): Promise<boolean> {
    return bcrypt.compare(password, hashedPassword);
  }
}

// 3. 请求验证
@Post()
@UsePipes(new ValidationPipe({ transform: true, whitelist: true }))
async create(@Body() createUserDto: CreateUserDto) {
  // ...
}

5. 性能优化 ​

typescript
// 1. 缓存策略
@Injectable()
export class CacheInterceptor implements NestInterceptor {
  constructor(private cacheManager: Cache) {}

  async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
    const key = this.generateKey(context);
    const cached = await this.cacheManager.get(key);
    
    if (cached) {
      return of(cached);
    }
    
    return next.handle().pipe(
      tap(response => this.cacheManager.set(key, response))
    );
  }
}

// 2. 数据库优化
@Injectable()
export class ProductsService {
  async findAll(query: QueryDto) {
    return this.productRepository
      .createQueryBuilder('product')
      .leftJoinAndSelect('product.category', 'category')
      .where(query.conditions)
      .take(query.limit)
      .skip(query.offset)
      .cache(true)
      .getMany();
  }
}

进阶主题 🚀 ​

  1. 微服务架构

    • 消息模式
    • gRPC 集成
    • 微服务通信
  2. GraphQL 集成

    • Schema 定义
    • 解析器
    • 订阅
  3. WebSocket 支持

    • 实时通信
    • 事件处理
    • 房间管理
  4. 任务调度

    • 定时任务
    • 队列处理
    • 后台作业

下一步学习建议 📈 ​

  1. 深入理解 TypeScript

    • 类型系统
    • 装饰器
    • 泛型
  2. 学习响应式编程

    • RxJS
    • 观察者模式
    • 流处理
  3. 数据库优化

    • 查询优化
    • 索引设计
    • 事务处理
  4. 测试实践

    • 单元测试
    • E2E 测试
    • 测试覆盖率

相关资源 📚 ​

结语 🎉 ​

通过这个系列,我们已经全面了解了 NestJS 的核心概念和最佳实践。NestJS 不仅提供了一个强大的框架,更重要的是它推广了很多优秀的设计理念和开发实践。希望这个系列能帮助你更好地使用 NestJS 开发企业级应用。

记住,编程是一个持续学习的过程,保持学习的热情,不断实践和探索新的可能性!