nestjs-patterns
하는 일
이 가이드는 NestJS 기술로 웹 애플리케이션을 정리하고 만드는 방법을 알려 줍니다. 코드를 모듈, 컨트롤러, 서비스 같은 부분으로 나누는 방법과, 받은 데이터가 올바르고 안전한지 확인하는 방법을 보여 줍니다.
사용하는 경우
- ✓NestJS로 새 웹 프로젝트를 시작할 때.
- ✓기존 NestJS 프로젝트의 코드를 정리할 때.
- ✓API에 데이터 검증이나 보안 규칙을 추가할 때.
스킬 링크
https://github.com/affaan-m/ECC/blob/main/pi/core/skills/nestjs-patterns/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“유지보수하기 쉽도록 NestJS 코드를 어떻게 정리할 수 있을까요?”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
역할별로 코드를 나누는 폴더 구조와 코드 예시를 제안합니다. 들어오는 데이터를 검증하는 방법과 오류를 일관되게 처리하는 방법을 보여 줍니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
NestJS Development Patterns
Production-grade NestJS patterns for modular TypeScript backends.
When to Activate
- Building NestJS APIs or services
- Structuring modules, controllers, and providers
- Adding DTO validation, guards, interceptors, or exception filters
- Configuring environment-aware settings and database integrations
- Testing NestJS units or HTTP endpoints
Project Structure
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/
- Keep domain code inside feature modules.
- Put cross-cutting filters, decorators, guards, and interceptors in
common/. - Keep DTOs close to the module that owns them.
Bootstrap and Global Validation
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();
- Always enable
whitelistandforbidNonWhitelistedon public APIs. - Prefer one global validation pipe instead of repeating validation config per route.
Modules, Controllers, and Providers
@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);
}
}
- Controllers should stay thin: parse HTTP input, call a provider, return response DTOs.
- Put business logic in injectable services, not controllers.
- Export only the providers other modules genuinely need.
DTOs and Validation
export class CreateUserDto {
@IsEmail()
email!: string;
@IsString()
@Length(2, 80)
name!: string;
@IsOptional()
@IsEnum(UserRole)
role?: UserRole;
}
- Validate every request DTO with
class-validator. - Use dedicated response DTOs or serializers instead of returning ORM entities directly.
- Avoid leaking internal fields such as password hashes, tokens, or audit columns.
Auth, Guards, and Request Context
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin')
@Get('admin/report')
getAdminReport(@Req() req: AuthenticatedRequest) {
return this.reportService.getForUser(req.user.id);
}
- Keep auth strategies and guards module-local unless they are truly shared.
- Encode coarse access rules in guards, then do resource-specific authorization in services.
- Prefer explicit request types for authenticated request objects.
Exception Filters and Error Shape
@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',
});
}
}
- Keep one consistent error envelope across the API.
- Throw framework exceptions for expected client errors; log and wrap unexpected failures centrally.
Config and Environment Validation
ConfigModule.forRoot({
isGlobal: true,
load: [configuration],
…
자주 묻는 질문
모듈, 컨트롤러, 프로바이더는 무엇인가요?
모듈은 코드를 정리하고, 컨트롤러는 요청을 처리하며, 프로바이더(서비스)는 업무 로직을 담당합니다.
들어오는 데이터를 검증하는 것이 왜 중요한가요?
애플리케이션이 예상된 안전한 정보만 받도록 해서, 오류와 보안 침해를 막기 위해서입니다.
애플리케이션의 오류는 어떻게 처리하나요?
가이드는 예외 필터를 사용해 사용자와 개발자에게 오류를 보고하는 방식을 표준화하라고 제안합니다.
상세 정보
작성자의 원본 설명
NestJS architecture patterns for modules, controllers, providers, DTO validation, guards, interceptors, config, and production-grade TypeScript backends. Use when building or reviewing a NestJS backend — modules, providers, DTO validation, guards, or interceptors.
repo: affaan-m/ECC
인기도
- GitHub 스타
- 280k
- 순위
- #216
- 라이선스
- MIT
- 업데이트
- 2026. 10. 15.
댓글
- …
이 저장소의 다른 스킬
accessibility
280k에이전트가 모든 사람이 쓸 수 있는 인터페이스를 만들도록 돕습니다. 시각 장애나 운동 장애가 있는 사람도 쓸 수 있게 합니다.
agent-architecture-audit
280k에이전트가 모든 것이 올바르게 작동하는지 점검하도록 돕습니다. AI 시스템의 문제를 찾아 고쳐서 기대대로 작동하게 합니다.
agent-eval
280k에이전트가 서로 다른 AI 코딩 도구를 비교하도록 돕습니다. 특정 작업에서 어느 도구가 더 빠르고, 저렴하고, 믿을 만한지 측정합니다.
agent-harness-construction
280k에이전트가 작업을 더 잘 이해하도록 돕습니다. 에이전트가 쓰는 도구와 지시문을 최적화해 성공 가능성을 높입니다.
비슷한 스킬
shopify
260kShopify GraphQL API로 상품, 재고, 주문, 고객 같은 스토어 데이터를 읽고 업데이트하도록 에이전트를 돕습니다.
rest-graphql-debug
260kREST나 GraphQL API 호출이 실패하는 이유를 찾도록 돕습니다. 연결, 로그인, 요청 형식, 응답을 한 층씩 확인합니다.
har-derived-api-client
260k웹사이트의 네트워크 트래픽을 한 번 기록해 직접 API 클라이언트를 만들도록 돕습니다. 매번 페이지를 클릭하지 않아도 됩니다.