Communitygithub.com

NestJS 模式

NestJS 架构模式,涵盖模块、控制器、提供者、DTO 验证、守卫、拦截器、配置及生产级 TypeScript 后端。适用于构建或审查 NestJS 后端——模块、提供者、DTO 验证、守卫或拦截器。

NestJS 模式 是什么?

此技能提供了一套全面的 NestJS 开发模式,旨在帮助开发人员构建生产级的模块化 TypeScript 后端。它涵盖了 NestJS 应用的核心架构元素,包括模块、控制器、服务提供者、数据传输对象(DTO)验证、守卫、拦截器和异常过滤器。该技能强调了清晰的模块化结构、跨切面关注点的分离(例如将公共过滤器、守卫和拦截器放在 common/ 目录下),以及将 DTO 与所属模块保持紧密关联。它还提供了关于启动引导、全局验证管道配置、认证与授权、异常处理、环境变量验证、数据库持久化和测试的最佳实践。这些模式适用于任何研发团队使用 NestJS 构建的 API 或服务,无论是新项目还是代码审查。通过遵循这些模式,开发者可以确保代码的一致性、可维护性和可扩展性,同时避免常见陷阱。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/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/ 或 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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

相关技能