Communitygithub.com

NestJS 開發模式

NestJS 架構模式,涵蓋模組、控制器、提供者、DTO 驗證、守衛、攔截器、設定及生產級 TypeScript 後端。在構建或審查 NestJS 後端時使用——包括模組、提供者、DTO 驗證、守衛或攔截器。

NestJS 開發模式 是什麼?

此技能提供了一套完整的 NestJS 開發模式,專注於生產級 TypeScript 後端的模組化架構。它涵蓋了從專案結構設計、全局驗證管線配置、模組與控制器及提供者的組合,到 DTO 驗證、身份驗證守衛、異常過濾器、設定驗證、持久化與交易處理,以及全面的測試策略。支援的平台包括 NestJS 框架本身,並整合 Prisma 或 TypeORM 等 ORM。使用此技能時,AI 應遵循標準的 NestJS 慣例,將領域程式碼放在功能模組中,跨橫切關注點(如過濾器、守衛、攔截器)放在 `common/` 目錄下,並保持 DTO 靠近所屬模組。它強調薄控制器、厚服務、統一的錯誤封包、環境變數啟動時驗證,以及生產環境的結構化日誌和健康檢查。此技能非常適合用於 Claude Code、Coder 或 Codex 等 AI 編碼代理,以生成或審查符合 NestJS 最佳實踐的後端程式碼。

相容平台~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 開發模式 是做什麼的?

生產級 NestJS 模式,用於模組化 TypeScript 後端。

啟用時機

  • 建置 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: 'Internal server 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.

相關技能