Communitygithub.com

nestjs-patterns

NestJS 架構模式,涵蓋模組、控制器、提供者、DTO 驗證、守衛、攔截器、配置與生產級 TypeScript 後端。適用於建置或審查 NestJS 後端 — 模組、提供者、DTO 驗證、守衛或攔截器。

nestjs-patterns 是什麼?

此技能提供了一套完整的 NestJS 開發模式,適用於建置生產級、模組化的 TypeScript 後端。它涵蓋了 NestJS 的核心概念,包括以特徵為基礎的專案結構引導、全域 DTO 驗證管線、控制器與服務的責任分離、安全守衛與攔截器、異常過濾器、型別化的環境配置,以及資料庫整合和測試策略。使用者可以獲得從初始引導、模組組織、驗證邏輯,到錯誤處理、環境配置和測試套件的具體指導。此技能支援 Claude Code、Cursor 與 Codex 等 AI 代理平台,確保在生成或審查 NestJS 程式碼時,能遵循模組化、安全性、可測試性和生產就緒的最佳實踐。透過遵循這些模式,開發者可以建置結構一致、易於維護且穩健的 NestJS 應用程式。

相容平台~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.

相關技能