实战

Claude Code + NestJS 实战:用 AI 构建企业级 TypeScript 后端服务

Claude Code 与 NestJS 框架深度协作实战:模块化架构设计(Module/Controller/Service/Provider)、让 Claude 生成符合 NestJS 惯例的 CRUD 模块、依赖注入系统的 AI 辅助使用、Guards 认证守卫(JWT/Role-based)、Interceptors 全局日志与请求变换、Pipes 数据验证(class-validator)、Exception Filters 统一异常处理、TypeORM 集成与数据库迁移、Swagger 文档自动生成,以及 NestJS 微服务(Microservices)架构入门。

2026/3/214分钟 阅读ClaudeEagle

NestJS 的强约定性(Decorators、DI、Module)既是优点也是学习曲线。 Claude Code 能帮你快速理解和生成符合 NestJS 惯例的代码,避免踩坑。

CLAUDE.md NestJS 专项配置

markdown
# CLAUDE.md(NestJS 项目)

## 项目架构
src/
  modules/         # 按业务领域划分模块
    users/
      users.module.ts
      users.controller.ts
      users.service.ts
      dto/           # 请求/响应 DTO(用 class-validator 装饰)
      entities/      # TypeORM 实体
  common/
    decorators/    # 自定义装饰器
    filters/       # Exception Filters
    guards/        # Guards(认证/授权)
    interceptors/  # Interceptors(日志/缓存/变换)
    pipes/         # 自定义 Pipes

## NestJS 约定
- Controller 只处理 HTTP 层(参数解析/响应格式化),不写业务逻辑
- 业务逻辑全在 Service 中
- 跨模块调用通过 Service 注入,不直接访问其他模块的 Repository
- DTO 必须用 class-validator 装饰,并在 ValidationPipe 中校验
- 所有 API 必须加 Swagger 装饰器

## 禁止
- 在 Controller 中直接调用 Repository/DB
- 跨模块直接引用 Entity(通过 Service 暴露接口)

快速生成 CRUD 模块

你:为博客文章功能生成完整的 NestJS CRUD 模块,包含: - Post 实体(id/title/content/authorId/createdAt) - CreatePostDto / UpdatePostDto(含 class-validator 校验) - PostsController(5个 CRUD 端点 + Swagger 装饰器) - PostsService(业务逻辑) - PostsModule(组装所有组件) Claude:生成 5 个文件: // posts/entities/post.entity.ts import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, ManyToOne } from 'typeorm'; @Entity('posts') export class Post { @PrimaryGeneratedColumn('uuid') id: string; @Column({ length: 200 }) title: string; @Column('text') content: string; @Column() authorId: string; @CreateDateColumn() createdAt: Date; } // posts/dto/create-post.dto.ts import { IsString, IsNotEmpty, MaxLength, MinLength } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; export class CreatePostDto { @ApiProperty({ description: '文章标题', example: '2026 年 AI 趋势' }) @IsString() @IsNotEmpty() @MaxLength(200) @MinLength(1) title: string; @ApiProperty({ description: '文章正文(Markdown)' }) @IsString() @IsNotEmpty() content: string; } // posts/posts.controller.ts import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards, ParseUUIDPipe } from '@nestjs/common'; import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger'; import { JwtAuthGuard } from '../common/guards/jwt-auth.guard'; import { CurrentUser } from '../common/decorators/current-user.decorator'; import { PostsService } from './posts.service'; import { CreatePostDto } from './dto/create-post.dto'; @ApiTags('文章') @Controller('posts') export class PostsController { constructor(private readonly postsService: PostsService) {} @Post() @UseGuards(JwtAuthGuard) @ApiBearerAuth() @ApiOperation({ summary: '创建文章' }) create(@Body() dto: CreatePostDto, @CurrentUser() userId: string) { return this.postsService.create(dto, userId); } @Get() @ApiOperation({ summary: '获取文章列表' }) findAll() { return this.postsService.findAll(); } @Get(':id') findOne(@Param('id', ParseUUIDPipe) id: string) { return this.postsService.findOne(id); } @Patch(':id') @UseGuards(JwtAuthGuard) update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdatePostDto, @CurrentUser() userId: string) { return this.postsService.update(id, dto, userId); } @Delete(':id') @UseGuards(JwtAuthGuard) remove(@Param('id', ParseUUIDPipe) id: string, @CurrentUser() userId: string) { return this.postsService.remove(id, userId); } }

JWT 认证 Guard

你:帮我实现 JWT 认证完整流程: 登录返回 accessToken + refreshToken、 JwtAuthGuard 自动验证 Bearer Token、 CurrentUser 装饰器注入当前用户 Claude: // common/guards/jwt-auth.guard.ts import { Injectable, ExecutionContext, UnauthorizedException } from '@nestjs/common'; import { AuthGuard } from '@nestjs/passport'; @Injectable() export class JwtAuthGuard extends AuthGuard('jwt') { canActivate(context: ExecutionContext) { return super.canActivate(context); } handleRequest(err, user) { if (err || !user) throw new UnauthorizedException('Token 无效或已过期'); return user; } } // common/decorators/current-user.decorator.ts import { createParamDecorator, ExecutionContext } from '@nestjs/common'; export const CurrentUser = createParamDecorator( (data: string | undefined, ctx: ExecutionContext) => { const request = ctx.switchToHttp().getRequest(); return data ? request.user?.[data] : request.user?.id; }, );

全局 Interceptor:统一响应格式

typescript
// common/interceptors/transform.interceptor.ts
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      map(data => ({
        code: 0,
        data,
        message: 'success',
        timestamp: new Date().toISOString(),
      }))
    );
  }
}

// main.ts 全局注册
app.useGlobalInterceptors(new TransformInterceptor());
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
app.useGlobalFilters(new HttpExceptionFilter());

Swagger 文档自动生成

typescript
// main.ts
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

const config = new DocumentBuilder()
  .setTitle('My API')
  .setDescription('API 文档')
  .setVersion('1.0')
  .addBearerAuth()
  .build();

const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api/docs', app, document);

// 访问 http://localhost:3000/api/docs 查看 Swagger UI
你:检查所有 Controller,补全缺失的 Swagger 装饰器: @ApiOperation、@ApiResponse、@ApiBody、@ApiParam Claude:扫描所有 Controller 文件,为缺少 Swagger 注释的端点逐一补全

来源:Claude Code 官方文档 - docs.anthropic.com/en/docs/claude-code

相关文章推荐

实战Claude Code 写 React 组件:从需求描述到单元测试的完整工作流Claude Code 开发 React 组件完整工作流:需求转组件设计、TypeScript Props 定义、Hooks 实现、Tailwind 样式、React Testing Library 测试、Storybook 文档,以及复杂组件(表格/表单/弹窗)的高效开发模式。2026/3/15实战Claude Code + Next.js 15 全栈开发实战:从零搭建现代 Web 应用Claude Code 与 Next.js 15 结合开发完整教程:App Router 结构生成、Server/Client Components、API Routes、Prisma 数据库集成、Tailwind CSS UI、NextAuth 认证、Vercel 部署,以及 Claude Code 加速 Next.js 开发的 10 个核心工作流。2026/3/15实战用 Claude Code 开发 Chrome 扩展:Manifest V3 + AI 助手从零到发布Claude Code 开发 Chrome 扩展完整实战:八步流程(项目规划/结构初始化/manifest.json/Service Worker/Popup+ContentScript/构建测试/MV3 坑点排查),含时效对比和三大关键经验。2026/3/14实战Claude Code 命令行工具开发实战:用 AI 快速构建专业 CLI 工具Claude Code 辅助命令行工具(CLI)开发的完整实战指南:Python Click/Typer、Go Cobra、Rust Clap 技术栈选型、用 Claude Code 生成完整 CLI 项目结构(参数解析/子命令/全局选项)、交互式提示和彩色输出、配置文件管理、Shell 自动补全生成、跨平台打包(PyInstaller/goreleaser),以及发布到 PyPI/npm/Homebrew 的完整流程。2026/3/26实战Claude Code Vue 3 实战完全指南:Composition API 开发到企业级前端工程化Claude Code 辅助 Vue 3 开发的完整实战指南:Composition API 组件生成(setup/ref/computed)、Pinia 状态管理代码生成、Vue Router 4 路由配置、TypeScript 类型定义生成(Props/Emits)、Composables 抽象、Vitest 单元测试生成、性能优化(虚拟滚动/v-memo),以及 Options API 迁移和响应式丢失问题排查的 Prompt 模板。2026/3/26实战Claude Code Django 实战完全指南:从模型设计到 REST API 开发全流程Claude Code 辅助 Django 开发的完整实战指南:用 Claude Code 生成 Django 项目结构和 Models(含迁移文件)、Django REST Framework(DRF)API 开发(Serializer/ViewSet/Router)、用户认证系统(JWT/Session/第三方登录)、Django ORM 查询优化(select_related/prefetch_related/annotate)、异步任务(Celery + Redis)、测试用例生成(pytest-django)、Docker 化部署,以及在现有 Django 项目中快速定位和修复 Bug 的 Prompt 技巧。2026/3/26