Communitygithub.com

NestJS 아키텍처 패턴

모듈, 컨트롤러, 프로바이더, DTO 검증, 가드, 인터셉터, 설정 및 프로덕션급 TypeScript 백엔드를 위한 NestJS 아키텍처 패턴입니다. NestJS 백엔드를 구축하거나 검토할 때 사용하세요.

NestJS 아키텍처 패턴란 무엇인가요?

이 스킬은 NestJS 애플리케이션 개발 시 모듈 구조화, 컨트롤러 및 프로바이더 설계, DTO 검증, 가드, 인터셉터, 예외 필터, 환경 설정, 데이터베이스 통합 및 테스트 전반에 대한 프로덕션 레벨의 모범 사례를 제공합니다. Claude Code, Cursor, Codex 등 다양한 AI 에이전트 플랫폼에서 사용할 수 있으며, `SKILL.md` 문서를 기반으로 개발자에게 일관된 패턴 가이드를 제시합니다. 이 스킬은 기능별 모듈, 공통 유틸리티 디렉토리 구조, 글로벌 ValidationPipe 설정, DTO별 class-validator 데코레이터 사용, 인증 및 권한 부여를 위한 가드 체인, 일관된 에러 응답 형식을 강조합니다. 또한 환경 변수 검증을 부트 시점에 수행하고, 단위 테스트와 HTTP 통합 테스트를 동일한 파이프라인으로 실행하는 방법을 안내합니다. 결과적으로 개발자는 반복적인 패턴 탐색 없이 안정적이고 확장 가능한 NestJS 백엔드를 신속하게 구축할 수 있습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/nestjs-patterns

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

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;
}
  • 모든 요청 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 전반에 걸쳐 일관된 하나의 에러 응답 형식을 유지하세요.
  • 예상되는 클라이언트 오류에는 프레임워크 예외를 던지고, 예상치 못한 실패는 중앙에서 로깅하고 래핑하세요.

설정 및 환경 변수 검증

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/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.

관련 스킬