mcpField
N
nestjs-best-practices

nestjs-best-practices

github.com/ejirocodes开发6448 次安装19 周前更新
代码仓库

关于 nestjs-best-practices

nestjs-best-practices 是面向 NestJS 11 开发者的实践参考技能,整理架构、请求处理、验证、认证、数据库、测试和微服务等主题。它还列出常见错误、建议模式及 NestJS 11 的变更。

主要功能

  1. 01涵盖模块、提供者与依赖注入
  2. 02参考请求生命周期处理模式
  3. 03介绍 DTO 验证与认证
  4. 04整理数据库集成与测试
  5. 05提供 OpenAPI、GraphQL 和微服务参考
  6. 06列出 NestJS 11 变更与常见错误

适用场景

  1. 01规划 NestJS 模块与服务结构
  2. 02实现请求验证和 JWT 认证
  3. 03配置数据库集成并编写测试
  4. 04排查循环依赖或异常处理问题

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/ejirocodes/agent-skills --skill nestjs-best-practices

安装后在 Claude Code 中输入/nestjs-best-practices确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
authentication.md
core-architecture.md
database-integration.md
microservices.md
openapi-graphql.md
request-lifecycle.md
testing.md
validation-pipes.md

详细介绍

NestJS 11 最佳实践

快速参考

主题适用场景参考
核心架构模块、提供者、DI、forwardRef、自定义装饰器core-architecture.md
请求生命周期中间件、守卫、拦截器、管道、过滤器request-lifecycle.md
验证与管道DTO、class-validator、ValidationPipe、转换validation-pipes.md
身份验证JWT、Passport、守卫、本地/OAuth 策略、RBACauthentication.md
数据库TypeORM、Prisma、Drizzle ORM、存储库模式database-integration.md
测试单元测试、E2E 测试、模拟提供者testing.md
OpenAPI 与 GraphQLSwagger 装饰器、解析器、订阅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 用户更新了适配器
  • 动态模块:多次导入配置相同的同一模块会创建不同实例

常见错误

  1. 循环依赖未使用 forwardRef() - 会导致“无法解析依赖项”错误;使用 forwardRef(() => ModuleName) 包装
  2. 抛出普通错误而非 HttpException - 会丢失状态码并破坏异常过滤器;使用 throw new BadRequestException('message')
  3. 缺少 @Injectable() 装饰器 - 提供者无法注入;始终为服务添加此装饰器
  4. 全局 ValidationPipe 未设置 whitelist: true - 会允许意外属性;设置 whitelist: true, forbidNonWhitelisted: true
  5. 导入模块而非导出提供者 - 使用 exports 数组在模块之间共享提供者
  6. 异步配置未使用 ConfigModule.forRoot() - ConfigService 未定义;在 AppModule 中导入 ConfigModule
  7. 测试未使用 overrideProvider() - 单元测试会使用真实服务;使用 overrideProvider(Service).useValue(mock) 模拟依赖项
  8. E2E 测试共享数据库状态 - 测试之间没有隔离;使用事务,或在 beforeEach 中清空表

评论

支持 Markdown