Communitygithub.com

NestJS 模式

用于模块、控制器、提供者、DTO 验证、守卫、拦截器、配置和生产级 TypeScript 后端的 NestJS 架构模式。在构建或审查 NestJS 后端时使用——涉及模块、提供者、DTO 验证、守卫或拦截器。

NestJS 模式 是什么?

该技能提供了构建生产级 NestJS 后端所需的完整架构指南和最佳实践模式。它涵盖了从项目结构设计(如功能模块、通用过滤器/守卫/拦截器存放于 common/ 目录)到核心实现细节(包括模块、控制器、提供者、DTO 验证、身份验证守卫、异常过滤器、配置验证以及持久化层)的方方面面。技能还强调了在 NestJS 单元测试和 HTTP 端点测试中复用生产级全局管道和过滤器的重要性。通过遵循这些模式,开发者可以确保 API 的一致性、可维护性和安全性,同时避免常见陷阱,如将业务逻辑泄漏到控制器中或泄露内部字段。该技能适用于所有 NestJS 版本,并支持包括 Prisma 和 TypeORM 在内的常见 ORM。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/nestjs-patterns

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

NestJS 开发模式

用于模块化 TypeScript 后端的生产级 NestJS 模式。

何时激活

  • 构建 NestJS API 或服务
  • 结构化模块、控制器和提供者
  • 添加 DTO 验证、守卫、拦截器或异常过滤器
  • 配置环境感知设置和数据库集成
  • 测试 NestJS 单元或 HTTP 端点

项目结构

src/
├── app.module.ts
├── main.ts
├── common/
│   ├── filters/
│   ├── guards/
│   ├── interceptors/
│   └── pipes/
├── config/
│   ├── configuration.ts
│   └── validation.ts
├── modules/
│   ├── auth/
│   │   ├── auth.controller.ts
│   │   ├── auth.module.ts
│   │   ├── auth.service.ts
│   │   ├── dto/
│   │   ├── guards/
│   │   └── strategies/
│   └── users/
│       ├── dto/
│       ├── entities/
│       ├── users.controller.ts
│       ├── users.module.ts
│       └── users.service.ts
└── prisma/ or database/
  • 将领域代码保留在功能模块内。
  • 将横切关注点的过滤器、装饰器、守卫和拦截器放到 common/ 中。
  • 让 DTO 靠近拥有它的模块。

引导与全局验证

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { bufferLogs: true });

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      transformOptions: { enableImplicitConversion: true },
    }),
  );

  app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
  app.useGlobalFilters(new HttpExceptionFilter());

  await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
  • 在公共 API 上始终启用 whitelist 和 forbidNonWhitelisted。
  • 优先使用一个全局验证管道,而不是在每个路由上重复验证配置。

模块、控制器和提供者

@Module({
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService],
})
export class UsersModule {}

@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get(':id')
  getById(@Param('id', ParseUUIDPipe) id: string) {
    return this.usersService.getById(id);
  }

  @Post()
  create(@Body() dto: CreateUserDto) {
    return this.usersService.create(dto);
  }
}

@Injectable()
export class UsersService {
  constructor(private readonly usersRepo: UsersRepository) {}

  async create(dto: CreateUserDto) {
    return this.usersRepo.create(dto);
  }
}
  • 控制器应保持简洁:解析 HTTP 输入,调用提供者,返回响应 DTO。
  • 将业务逻辑放在可注入的服务中,而不是控制器中。
  • 只导出其他模块真正需要的提供者。

DTO 与验证

export class CreateUserDto {
  @IsEmail()
  email!: string;

  @IsString()
  @Length(2, 80)
  name!: string;

  @IsOptional()
  @IsEnum(UserRole)
  role?: UserRole;
}
  • 使用 class-validator 验证每个请求 DTO。
  • 使用专用的响应 DTO 或序列化器,而不是直接返回 ORM 实体。
  • 避免泄漏内部字段,如密码哈希、令牌或审计列。

认证、守卫与请求上下文

@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin')
@Get('admin/report')
getAdminReport(@Req() req: AuthenticatedRequest) {
  return this.reportService.getForUser(req.user.id);
}
  • 让认证策略和守卫保持模块本地化,除非它们是真正共享的。
  • 在守卫中编码粗粒度的访问规则,然后在实际的资源授权逻辑中执行更细粒度的检查。
  • 对于已认证的请求对象,优先使用明确的请求类型。

异常过滤器与错误格式

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse<Response>();
    const request = host.switchToHttp().getRequest<Request>();

    if (exception instanceof HttpException) {
      return response.status(exception.getStatus()).json({
        path: request.url,
        error: exception.getResponse(),
      });
    }

    return response.status(500).json({
      path: request.url,
      error: '内部服务器错误',
    });
  }
}
  • 在整个 API 中保持一致的错误结构。
  • 对预期的客户端错误抛出框架异常;在中心位置记录并包装意外故障。

配置与环境验证

ConfigModule.forRoot({
  isGlobal: true,
  load: [configuration],
  validate: validateEnv,
});
  • 在启动时验证环境变量,而不是在第一次请求时延迟验证。
  • 将配置访问限制在类型化的辅助函数或配置服务之后。
  • 在配置工厂中分离开发/预发布/生产环境的关注点,而不是在整个功能代码中分支。

持久化与事务

  • 将存储库 / ORM 代码隐藏在讲领域语言的提供者后面。
  • 对于 Prisma 或 TypeORM,将事务性工作流隔离在拥有工作单元的服务中。
  • 不要让控制器直接协调多步写入操作。

测试

describe('UsersController', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [UsersModule],
    }).compile();

    app = moduleRef.createNestApplication();
    app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
    await app.init();
  });
});
  • 使用模拟依赖项隔离地对提供者进行单元测试。
  • 为守卫、验证管道和异常过滤器添加请求级别的测试。
  • 在测试中复用与生产环境相同的全局管道/过滤器。

生产默认值

  • 启用结构化日志记录和请求关联 ID。
  • 遇到无效的环境变量/配置时终止,而不是部分启动。
  • 优先使用显式健康检查的异步提供者初始化,用于数据库/缓存客户端。
  • 将后台任务和事件消费者放在它们自己的模块中,而不是 HTTP 控制器内部。
  • 对公共端点明确实施速率限制、认证和审计日志记录。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相关技能