Communitygithub.com

NestJS 開発パターン

モジュール、コントローラ、プロバイダ、DTOバリデーション、ガード、インターセプタ、設定、本番グレードのTypeScriptバックエンドのためのNestJSアーキテクチャパターン。NestJSバックエンドの構築やレビュー時に使用します。

NestJS 開発パターン とは?

このスキルは、NestJSを使用した本番グレードのTypeScriptバックエンド開発のための包括的なアーキテクチャパターンとベストプラクティスを提供します。モジュール構成、コントローラとプロバイダの責務分離、DTOバリデーション、ガードやインターセプタ、例外フィルタなどのクロスカッティング関心事の実装方法を具体的なコード例とともに示します。また、環境設定の検証、PrismaやTypeORMを使ったデータベース連携、単体テストや結合テストの実践的なアプローチについても解説しています。このスキルは主にClaude CodeやCursorなどのAIエージェントがNestJSプロジェクトのコード生成、レビュー、リファクタリングを行う際に活用できます。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/nestjs-patterns

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

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 を有効にします。
  • ルートごとにバリデーション設定を繰り返す代わりに、1つのグローバルバリデーションパイプを使用することを推奨します。

モジュール、コントローラ、プロバイダ

@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;
}
  • すべてのリクエストDTOを class-validator でバリデーションします。
  • ORMエンティティを直接返す代わりに、専用のレスポンスDTOやシリアライザを使用します。
  • パスワードハッシュ、トークン、監査列などの内部フィールドを漏洩させないようにします。

認証、ガード、リクエストコンテキスト

@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全体で一貫した1つのエラーエンベロープを維持します。
  • 期待されるクライアントエラーにはフレームワークの例外をスローし、予期しない障害は中央でログ出力してラップします。

設定と環境バリデーション

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を有効にします。
  • 環境変数/設定が無効な場合は、部分的に起動するのではなく終了します。
  • DB/キャッシュクライアントの非同期プロバイダ初期化を明示的なヘルスチェックと共に推奨します。
  • バックグラウンドジョブやイベントコンシューマは、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.

関連スキル