关于 nestjs-best-practices
nestjs-best-practices 是面向 NestJS 11 开发者的实践参考技能,整理架构、请求处理、验证、认证、数据库、测试和微服务等主题。它还列出常见错误、建议模式及 NestJS 11 的变更。
主要功能
- 01涵盖模块、提供者与依赖注入
- 02参考请求生命周期处理模式
- 03介绍 DTO 验证与认证
- 04整理数据库集成与测试
- 05提供 OpenAPI、GraphQL 和微服务参考
- 06列出 NestJS 11 变更与常见错误
适用场景
- 01规划 NestJS 模块与服务结构
- 02实现请求验证和 JWT 认证
- 03配置数据库集成并编写测试
- 04排查循环依赖或异常处理问题
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ ejirocodes/ agent-skills --skill nestjs-best-practices安装后在 Claude Code 中输入/nestjs-best-practices确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/authentication.mdcore-architecture.mddatabase-integration.mdmicroservices.mdopenapi-graphql.mdrequest-lifecycle.mdtesting.mdvalidation-pipes.md详细介绍
NestJS 11 最佳实践
快速参考
| 主题 | 适用场景 | 参考 |
|---|---|---|
| 核心架构 | 模块、提供者、DI、forwardRef、自定义装饰器 | core-architecture.md |
| 请求生命周期 | 中间件、守卫、拦截器、管道、过滤器 | request-lifecycle.md |
| 验证与管道 | DTO、class-validator、ValidationPipe、转换 | validation-pipes.md |
| 身份验证 | JWT、Passport、守卫、本地/OAuth 策略、RBAC | authentication.md |
| 数据库 | TypeORM、Prisma、Drizzle ORM、存储库模式 | database-integration.md |
| 测试 | 单元测试、E2E 测试、模拟提供者 | testing.md |
| OpenAPI 与 GraphQL | Swagger 装饰器、解析器、订阅 | openapi-graphql.md |
| 微服务 | TCP、Redis、NATS、Kafka 模式 | microservices.md |
核心模式
带提供者的模块
@Module({
imports: [DatabaseModule],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService], // Export for other modules
})
export class UsersModule {}
带验证的控制器
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post()
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.usersService.findOne(id);
}
}
带验证的 DTO
import { IsEmail, IsString, MinLength, IsOptional } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsString()
@MinLength(8)
password: string;
@IsOptional()
@IsString()
name?: string;
}
异常过滤器
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
response.status(status).json({
statusCode: status,
message: exception.message,
timestamp: new Date().toISOString(),
});
}
}
带 JWT 的守卫
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
}
NestJS 11 重大变更
- Express v5:通配符必须命名(例如,
*splat),可选参数使用花括号/:file{.:ext} - Node.js 20+:最低要求版本
- Fastify v5:为 Fastify 用户更新了适配器
- 动态模块:多次导入配置相同的同一模块会创建不同实例
常见错误
- 循环依赖未使用
forwardRef()- 会导致“无法解析依赖项”错误;使用forwardRef(() => ModuleName)包装 - 抛出普通错误而非 HttpException - 会丢失状态码并破坏异常过滤器;使用
throw new BadRequestException('message') - 缺少
@Injectable()装饰器 - 提供者无法注入;始终为服务添加此装饰器 - 全局 ValidationPipe 未设置
whitelist: true- 会允许意外属性;设置whitelist: true, forbidNonWhitelisted: true - 导入模块而非导出提供者 - 使用
exports数组在模块之间共享提供者 - 异步配置未使用
ConfigModule.forRoot()- ConfigService 未定义;在 AppModule 中导入 ConfigModule - 测试未使用
overrideProvider()- 单元测试会使用真实服务;使用overrideProvider(Service).useValue(mock)模拟依赖项 - E2E 测试共享数据库状态 - 测试之间没有隔离;使用事务,或在 beforeEach 中清空表
评论
支持 Markdown