nestjs-code-review by giuseppe-trisciuoglio/developer-kit
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill nestjs-code-review此技能为 NestJS 应用程序提供结构化、全面的代码审查。它根据 NestJS 最佳实践、TypeScript 约定、SOLID 原则和生产就绪标准来评估代码。审查会产生按严重性(严重、警告、建议)分类的可操作发现项,并提供具体的代码改进示例。
当通过代理系统调用时,此技能会委托给 nestjs-code-review-expert 代理进行深度分析。
@Controller、@Injectable、@Module 等)的正确使用确定范围:确定要审查哪些 NestJS 文件和模块。使用 glob 和 grep 来发现目标区域中的控制器、服务、模块、守卫、拦截器和管道。
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
分析模块结构:验证模块组织是否正确 —— 每个功能应有自己的模块,并明确定义导入、控制器、提供者和导出。检查循环依赖和正确的模块边界。
审查依赖注入:验证所有可注入服务是否使用构造函数注入。检查提供者作用域(单例、请求、瞬态)是否符合预期的生命周期。确保没有直接实例化绕过 DI 容器。
评估控制器:审查 HTTP 方法使用、路由命名、状态码、请求/响应 DTO、验证管道和 OpenAPI 装饰器。确认控制器是轻量的 —— 业务逻辑应属于服务。
评估服务与业务逻辑:检查服务是否正确封装了业务逻辑。验证错误处理、事务管理以及与基础设施关注点的适当分离。查找方法过大或职责过多的服务方法。
检查安全性:审查守卫实现、身份验证/授权模式、使用 class-validator 的输入验证,以及对常见漏洞(注入、XSS、CSRF)的防护。
审查测试:评估控制器、服务、守卫和管道的测试覆盖率。验证正确的模拟策略,并确保测试验证的是行为而非实现细节。
生成审查报告:生成一份结构化报告,包含按严重性分类的发现项(严重、警告、建议)、积极的观察结果,以及带有代码示例的优先建议。
// ❌ 不良做法:包含业务逻辑且缺少验证的臃肿控制器
@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: '创建新用户' })
@ApiResponse({ status: 201, type: UserResponseDto })
async create(
@Body(ValidationPipe) createUserDto: CreateUserDto,
): Promise<UserResponseDto> {
return this.userService.create(createUserDto);
}
}
// ❌ 不良做法:直接实例化绕过 DI
@Injectable()
export class OrderService {
private readonly logger = new Logger();
private readonly emailService = new EmailService();
async createOrder(dto: CreateOrderDto) {
this.emailService.send(dto.email, '订单已创建');
}
}
// ✅ 良好做法:正确的构造函数注入
@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, '订单已创建');
return order;
}
}
// ❌ 不良做法:带有信息泄露的通用错误处理
@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(`未找到 ID 为 ${id} 的用户`);
}
return user;
}
// ❌ 不良做法:授权逻辑在控制器中
@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();
}
// ❌ 不良做法:包含所有内容的单体模块
@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 {}
将所有代码审查发现项按以下结构组织:
简要概述,包含总体质量评分(1-10)和关键观察结果。
可能导致安全漏洞、数据损坏或生产故障的问题。
违反最佳实践、降低可维护性或可能导致错误的问题。
针对代码可读性、性能或开发者体验的改进建议。
已良好实现的模式和优秀实践,予以认可和鼓励。
按优先级排序的后续步骤,并提供最具影响力的改进代码示例。
ParseUUIDPipe、ParseIntPipe 等HttpException 的领域特定异常类new@ApiTags、@ApiOperation、@ApiResponse)查看 references/ 目录以获取详细的审查清单和模式文档:
references/patterns.md —— 包含示例的 NestJS 最佳实践模式references/anti-patterns.md —— 审查期间需要标记的常见 NestJS 反模式references/checklist.md —— 按领域组织的全面审查清单每周安装量
131
代码仓库
GitHub 星标数
173
首次出现
2026年2月28日
安全审计
安装于
codex117
gemini-cli117
github-copilot114
kimi-cli112
amp112
cline112
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.
@Controller, @Injectable, @Module, etc.)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.
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.
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.
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.
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.
Check Security : Review guard implementations, authentication/authorization patterns, input validation with class-validator, and protection against common vulnerabilities (injection, XSS, CSRF).
Review Testing : Assess test coverage for controllers, services, guards, and pipes. Verify proper mocking strategies and that tests validate behavior, not implementation details.
// ❌ 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);
}
}
// ❌ 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;
}
}
// ❌ 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;
}
// ❌ 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();
}
// ❌ 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 {}
Structure all code review findings as follows:
Brief overview with an overall quality score (1-10) and key observations.
Issues that could cause security vulnerabilities, data corruption, or production failures.
Issues that violate best practices, reduce maintainability, or could lead to bugs.
Improvements for code readability, performance, or developer experience.
Well-implemented patterns and good practices to acknowledge and encourage.
Prioritized next steps with code examples for the most impactful improvements.
ParseUUIDPipe, ParseIntPipe, etc. for parameter validationHttpExceptionnew for injectable services@ApiTags, @ApiOperation, @ApiResponse) to all endpointsSee the references/ directory for detailed review checklists and pattern documentation:
references/patterns.md — NestJS best practice patterns with examplesreferences/anti-patterns.md — Common NestJS anti-patterns to flag during reviewreferences/checklist.md — Comprehensive review checklist organized by areaWeekly Installs
131
Repository
GitHub Stars
173
First Seen
Feb 28, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
codex117
gemini-cli117
github-copilot114
kimi-cli112
amp112
cline112
Node.js 环境配置指南:多环境管理、类型安全与最佳实践
10,500 周安装
Saga编排模式详解:分布式事务与长时间业务流程管理解决方案
130 周安装
Bazel构建优化指南:大规模单体仓库配置、远程缓存与性能调优
125 周安装
Google Slides API 集成工具:无需MCP服务器,实现演示文稿自动化读写与管理
106 周安装
Transformers.js - 在浏览器和Node.js中运行Hugging Face机器学习模型
158 周安装
Claude代码配置健康审计工具:六层框架检测项目设置违规与层级校准
112 周安装
XcodeBuildMCP:替代xcodebuild的iOS/macOS开发自动化与调试工具
94 周安装
Produce Review Report : Generate a structured report with severity-classified findings (Critical, Warning, Suggestion), positive observations, and prioritized recommendations with code examples.