nestjs-code-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

NestJS Code Review

NestJS代码审查

Overview

概述

This skill provides structured, comprehensive code review for NestJS applications. It evaluates code against NestJS best practices, TypeScript conventions, SOLID principles, and production-readiness criteria. The review produces actionable findings categorized by severity (Critical, Warning, Suggestion) with concrete code examples for improvements.
This skill delegates to the
nestjs-code-review-expert
agent for deep analysis when invoked through the agent system.
本Skill为NestJS应用提供结构化、全面的代码审查服务。它会根据NestJS最佳实践、TypeScript规范、SOLID原则以及生产就绪标准对代码进行评估。审查结果会按照严重程度(Critical、Warning、Suggestion)分类,并附带具体的代码改进示例。
当通过Agent系统调用时,本Skill会委托给
nestjs-code-review-expert
Agent进行深度分析。

When to Use

使用场景

  • Reviewing NestJS controllers, services, modules, or providers before merging
  • Validating proper use of decorators (
    @Controller
    ,
    @Injectable
    ,
    @Module
    , etc.)
  • Checking dependency injection patterns and provider scoping
  • Reviewing REST API endpoints for standards compliance
  • Evaluating error handling with exception filters
  • Assessing guard and interceptor implementations
  • Reviewing database integration (TypeORM, Prisma, Drizzle ORM)
  • Validating DTO definitions and validation pipes
  • After implementing new NestJS features or refactoring modules
  • Checking microservices patterns (message/event patterns, transport layers)
  • 合并前审查NestJS控制器、服务、模块或提供者
  • 验证装饰器(
    @Controller
    @Injectable
    @Module
    等)的正确使用
  • 检查依赖注入模式和提供者作用域
  • 审查REST API端点是否符合标准规范
  • 评估异常过滤器的错误处理能力
  • 评估守卫和拦截器的实现
  • 审查数据库集成(TypeORM、Prisma、Drizzle ORM)
  • 验证DTO定义和验证管道
  • 实现新NestJS功能或重构模块后
  • 检查微服务模式(消息/事件模式、传输层)

Instructions

操作步骤

  1. Identify Scope: Determine which NestJS files and modules are under review. Use
    glob
    and
    grep
    to discover controllers, services, modules, guards, interceptors, and pipes in the target area.
  2. Analyze Module Structure: Verify proper module organization — each feature should have its own module with clearly defined imports, controllers, providers, and exports. Check for circular dependencies and proper module boundaries.
  3. Review Dependency Injection: Validate that all injectable services use constructor injection. Check provider scoping (singleton, request, transient) matches the intended lifecycle. Ensure no direct instantiation bypasses the DI container.
  4. Evaluate Controllers: Review HTTP method usage, route naming, status codes, request/response DTOs, validation pipes, and OpenAPI decorators. Confirm controllers are thin — business logic belongs in services.
  5. Assess Services & Business Logic: Check that services encapsulate business logic properly. Verify error handling, transaction management, and proper separation from infrastructure concerns. Look for service methods that are too large or have too many responsibilities.
  6. Check Security: Review guard implementations, authentication/authorization patterns, input validation with class-validator, and protection against common vulnerabilities (injection, XSS, CSRF).
  7. Review Testing: Assess test coverage for controllers, services, guards, and pipes. Verify proper mocking strategies and that tests validate behavior, not implementation details.
  8. Produce Review Report: Generate a structured report with severity-classified findings (Critical, Warning, Suggestion), positive observations, and prioritized recommendations with code examples.
  1. 确定范围:确定要审查的NestJS文件和模块。使用
    glob
    grep
    在目标区域中查找控制器、服务、模块、守卫、拦截器和管道。
  2. 分析模块结构:验证模块组织是否合理——每个功能应拥有独立模块,明确定义导入、控制器、提供者和导出。检查是否存在循环依赖以及模块边界是否合理。
  3. 审查依赖注入:验证所有可注入服务是否使用构造函数注入。检查提供者作用域(singleton、request、transient)是否与预期生命周期匹配。确保没有通过直接实例化绕过DI容器的情况。
  4. 评估控制器:审查HTTP方法使用、路由命名、状态码、请求/响应DTO、验证管道和OpenAPI装饰器。确认控制器保持轻量化——业务逻辑应委托给服务处理。
  5. 评估服务与业务逻辑:检查服务是否正确封装业务逻辑。验证错误处理、事务管理以及与基础设施关注点的分离情况。留意职责过多或代码量过大的服务方法。
  6. 安全检查:审查守卫实现、认证/授权模式、基于class-validator的输入验证,以及对常见漏洞(注入、XSS、CSRF)的防护。
  7. 审查测试:评估控制器、服务、守卫和管道的测试覆盖率。验证模拟策略是否恰当,测试是否验证行为而非实现细节。
  8. 生成审查报告:生成结构化报告,包含按严重程度分类的问题(Critical、Warning、Suggestion)、正面评价以及附带代码示例的优先级改进建议。

Examples

示例

Example 1: Reviewing a Controller

示例1:审查控制器

typescript
// ❌ Bad: Fat controller with business logic and missing validation
@Controller('users')
export class UserController {
  constructor(private readonly userRepo: Repository<User>) {}

  @Post()
  async create(@Body() body: any) {
    const user = this.userRepo.create(body);
    return this.userRepo.save(user);
  }
}

// ✅ Good: Thin controller with proper DTOs, validation, and service delegation
@Controller('users')
@ApiTags('Users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: 'Create a new user' })
  @ApiResponse({ status: 201, type: UserResponseDto })
  async create(
    @Body(ValidationPipe) createUserDto: CreateUserDto,
  ): Promise<UserResponseDto> {
    return this.userService.create(createUserDto);
  }
}
typescript
// ❌ 不良示例:包含业务逻辑的臃肿控制器,缺少验证
@Controller('users')
export class UserController {
  constructor(private readonly userRepo: Repository<User>) {}

  @Post()
  async create(@Body() body: any) {
    const user = this.userRepo.create(body);
    return this.userRepo.save(user);
  }
}

// ✅ 良好示例:轻量化控制器,使用正确的DTO、验证并委托给服务
@Controller('users')
@ApiTags('Users')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: 'Create a new user' })
  @ApiResponse({ status: 201, type: UserResponseDto })
  async create(
    @Body(ValidationPipe) createUserDto: CreateUserDto,
  ): Promise<UserResponseDto> {
    return this.userService.create(createUserDto);
  }
}

Example 2: Reviewing Dependency Injection

示例2:审查依赖注入

typescript
// ❌ Bad: Direct instantiation bypasses DI
@Injectable()
export class OrderService {
  private readonly logger = new Logger();
  private readonly emailService = new EmailService();

  async createOrder(dto: CreateOrderDto) {
    this.emailService.send(dto.email, 'Order created');
  }
}

// ✅ Good: Proper constructor injection
@Injectable()
export class OrderService {
  private readonly logger = new Logger(OrderService.name);

  constructor(
    private readonly orderRepository: OrderRepository,
    private readonly emailService: EmailService,
  ) {}

  async createOrder(dto: CreateOrderDto): Promise<Order> {
    const order = await this.orderRepository.create(dto);
    await this.emailService.send(dto.email, 'Order created');
    return order;
  }
}
typescript
// ❌ 不良示例:直接实例化绕过DI
@Injectable()
export class OrderService {
  private readonly logger = new Logger();
  private readonly emailService = new EmailService();

  async createOrder(dto: CreateOrderDto) {
    this.emailService.send(dto.email, 'Order created');
  }
}

// ✅ 良好示例:正确的构造函数注入
@Injectable()
export class OrderService {
  private readonly logger = new Logger(OrderService.name);

  constructor(
    private readonly orderRepository: OrderRepository,
    private readonly emailService: EmailService,
  ) {}

  async createOrder(dto: CreateOrderDto): Promise<Order> {
    const order = await this.orderRepository.create(dto);
    await this.emailService.send(dto.email, 'Order created');
    return order;
  }
}

Example 3: Reviewing Error Handling

示例3:审查错误处理

typescript
// ❌ Bad: Generic error handling with information leakage
@Get(':id')
async findOne(@Param('id') id: string) {
  try {
    return await this.service.findOne(id);
  } catch (error) {
    throw new HttpException(error.message, 500);
  }
}

// ✅ Good: Domain-specific exceptions with proper HTTP mapping
@Get(':id')
async findOne(@Param('id', ParseUUIDPipe) id: string): Promise<UserResponseDto> {
  const user = await this.userService.findOne(id);
  if (!user) {
    throw new NotFoundException(`User with ID ${id} not found`);
  }
  return user;
}
typescript
// ❌ 不良示例:通用错误处理,存在信息泄露
@Get(':id')
async findOne(@Param('id') id: string) {
  try {
    return await this.service.findOne(id);
  } catch (error) {
    throw new HttpException(error.message, 500);
  }
}

// ✅ 良好示例:领域特定异常,正确映射HTTP状态
@Get(':id')
async findOne(@Param('id', ParseUUIDPipe) id: string): Promise<UserResponseDto> {
  const user = await this.userService.findOne(id);
  if (!user) {
    throw new NotFoundException(`User with ID ${id} not found`);
  }
  return user;
}

Example 4: Reviewing Guard Implementation

示例4:审查守卫实现

typescript
// ❌ Bad: Authorization logic in controller
@Get('admin/dashboard')
async getDashboard(@Req() req: Request) {
  if (req.user.role !== 'admin') {
    throw new ForbiddenException();
  }
  return this.dashboardService.getData();
}

// ✅ Good: Guard-based authorization with decorator
@Get('admin/dashboard')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMIN)
async getDashboard(): Promise<DashboardDto> {
  return this.dashboardService.getData();
}
typescript
// ❌ 不良示例:控制器内包含授权逻辑
@Get('admin/dashboard')
async getDashboard(@Req() req: Request) {
  if (req.user.role !== 'admin') {
    throw new ForbiddenException();
  }
  return this.dashboardService.getData();
}

// ✅ 良好示例:基于守卫的授权,配合装饰器使用
@Get('admin/dashboard')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMIN)
async getDashboard(): Promise<DashboardDto> {
  return this.dashboardService.getData();
}

Example 5: Reviewing Module Organization

示例5:审查模块组织

typescript
// ❌ Bad: Monolithic module with everything
@Module({
  imports: [TypeOrmModule.forFeature([User, Order, Product, Review])],
  controllers: [UserController, OrderController, ProductController],
  providers: [UserService, OrderService, ProductService, ReviewService],
})
export class AppModule {}

// ✅ Good: Feature-based module organization
@Module({
  imports: [UserModule, OrderModule, ProductModule],
})
export class AppModule {}

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UserController],
  providers: [UserService, UserRepository],
  exports: [UserService],
})
export class UserModule {}
typescript
// ❌ 不良示例:包含所有内容的单体模块
@Module({
  imports: [TypeOrmModule.forFeature([User, Order, Product, Review])],
  controllers: [UserController, OrderController, ProductController],
  providers: [UserService, OrderService, ProductService, ReviewService],
})
export class AppModule {}

// ✅ 良好示例:基于功能的模块组织
@Module({
  imports: [UserModule, OrderModule, ProductModule],
})
export class AppModule {}

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  controllers: [UserController],
  providers: [UserService, UserRepository],
  exports: [UserService],
})
export class UserModule {}

Review Output Format

审查输出格式

Structure all code review findings as follows:
所有代码审查结果需按以下结构整理:

1. Summary

1. 摘要

Brief overview with an overall quality score (1-10) and key observations.
简要概述整体质量评分(1-10分)和关键观察结果。

2. Critical Issues (Must Fix)

2. 严重问题(必须修复)

Issues that could cause security vulnerabilities, data corruption, or production failures.
可能导致安全漏洞、数据损坏或生产故障的问题。

3. Warnings (Should Fix)

3. 警告(应该修复)

Issues that violate best practices, reduce maintainability, or could lead to bugs.
违反最佳实践、降低可维护性或可能引发bug的问题。

4. Suggestions (Consider Improving)

4. 建议(考虑改进)

Improvements for code readability, performance, or developer experience.
针对代码可读性、性能或开发者体验的改进建议。

5. Positive Observations

5. 正面评价

Well-implemented patterns and good practices to acknowledge and encourage.
对已正确实现的模式和最佳实践予以认可和鼓励。

6. Recommendations

6. 建议

Prioritized next steps with code examples for the most impactful improvements.
优先级排序的后续步骤,附带影响最大的改进方案代码示例。

Best Practices

最佳实践

  • Controllers should be thin — delegate all business logic to services
  • Use DTOs with class-validator for all request/response payloads
  • Apply
    ParseUUIDPipe
    ,
    ParseIntPipe
    , etc. for parameter validation
  • Use domain-specific exception classes extending
    HttpException
  • Organize code into feature modules with clear boundaries and exports
  • Prefer constructor injection — never use
    new
    for injectable services
  • Apply guards for authentication and authorization, not inline checks
  • Use interceptors for cross-cutting concerns (logging, caching, transformation)
  • Add OpenAPI decorators (
    @ApiTags
    ,
    @ApiOperation
    ,
    @ApiResponse
    ) to all endpoints
  • Write unit tests for services and integration tests for controllers
  • 控制器应保持轻量化——所有业务逻辑委托给服务处理
  • 对所有请求/响应负载使用带class-validator的DTO
  • 使用
    ParseUUIDPipe
    ParseIntPipe
    等进行参数验证
  • 使用继承自
    HttpException
    的领域特定异常类
  • 按功能组织代码,模块边界清晰并合理导出
  • 优先使用构造函数注入——绝不直接实例化可注入服务
  • 使用守卫处理认证和授权,而非内联检查
  • 使用拦截器处理横切关注点(日志、缓存、转换)
  • 为所有端点添加OpenAPI装饰器(
    @ApiTags
    @ApiOperation
    @ApiResponse
  • 为服务编写单元测试,为控制器编写集成测试

Constraints and Warnings

约束与注意事项

  • Do not enforce a single ORM — the codebase may use TypeORM, Prisma, Drizzle, or MikroORM
  • Respect existing project conventions even if they differ from NestJS defaults
  • Focus on high-confidence issues — avoid false positives on style preferences
  • When reviewing microservices patterns, consider transport-layer specific constraints
  • Do not suggest architectural rewrites unless critical issues warrant them
  • 不强制使用单一ORM——代码库可能使用TypeORM、Prisma、Drizzle或MikroORM
  • 尊重现有项目约定,即使与NestJS默认规范不同
  • 聚焦高可信度问题——避免对风格偏好误报
  • 审查微服务模式时,考虑传输层的特定约束
  • 除非存在严重问题,否则不建议进行架构重写

References

参考资料

See the
references/
directory for detailed review checklists and pattern documentation:
  • references/patterns.md
    — NestJS best practice patterns with examples
  • references/anti-patterns.md
    — Common NestJS anti-patterns to flag during review
  • references/checklist.md
    — Comprehensive review checklist organized by area
查看
references/
目录获取详细的审查清单和模式文档:
  • references/patterns.md
    ——带示例的NestJS最佳实践模式
  • references/anti-patterns.md
    ——代码审查中需标记的常见NestJS反模式
  • references/checklist.md
    ——按领域分类的全面审查清单