← 홈

🐱

⌘K
🤖
Claude Code AI 도구
🤗
Hugging Face AI 도구
🦜
LangChain AI 도구
🧠
Keras AI 도구
🦙
Ollama AI 도구
🐍
Python 프로그래밍 언어
🟨
JavaScript 프로그래밍 언어
🔷
TypeScript 프로그래밍 언어
⚛️
React 프로그래밍 언어
🐹
Go 프로그래밍 언어
🦀
Rust 프로그래밍 언어
📊
MATLAB 프로그래밍 언어
🗄️
SQL 프로그래밍 언어
⚙️
C/C++ 프로그래밍 언어
Java 프로그래밍 언어
🟣
C# 프로그래밍 언어
🍎
Swift 프로그래밍 언어
🟠
Kotlin 프로그래밍 언어
Next.js 프로그래밍 언어
💚
Vue.js 프로그래밍 언어
🔥
Svelte 프로그래밍 언어
🎨
Tailwind CSS 프로그래밍 언어
💚
Node.js 프로그래밍 언어
🌐
HTML 프로그래밍 언어
🎨
CSS/SCSS 프로그래밍 언어
🐘
PHP 프로그래밍 언어
💎
Ruby 프로그래밍 언어
🔴
Scala 프로그래밍 언어
📊
R 프로그래밍 언어
🎯
Dart 프로그래밍 언어
💧
Elixir 프로그래밍 언어
🌙
Lua 프로그래밍 언어
🐪
Perl 프로그래밍 언어
🅰️
Angular 프로그래밍 언어
🚂
Express.js 프로그래밍 언어
🐱
NestJS 프로그래밍 언어
🛤️
Ruby on Rails 프로그래밍 언어
◼️
GraphQL 프로그래밍 언어
🟪
Haskell 프로그래밍 언어
💚
Nuxt.js 프로그래밍 언어
🔷
SolidJS 프로그래밍 언어
htmx 프로그래밍 언어
💻
VS Code 개발 도구
🧠
PyCharm 개발 도구
📓
Jupyter 개발 도구
🧠
IntelliJ IDEA 개발 도구
💚
Neovim 개발 도구
🔮
Emacs 개발 도구
🔀
Git DevOps & CLI
🐳
Docker DevOps & CLI
☸️
Kubernetes DevOps & CLI
☁️
AWS CLI DevOps & CLI
🔄
GitHub Actions DevOps & CLI
🐧
Linux 명령어 DevOps & CLI
💻
Bash 스크립팅 DevOps & CLI
🌐
Nginx DevOps & CLI
📝
Vim DevOps & CLI
🔨
Makefile DevOps & CLI
🧪
Pytest DevOps & CLI
🪟
Windows DevOps & CLI
📦
패키지 매니저 DevOps & CLI
🍎
macOS DevOps & CLI
🏗️
Terraform DevOps & CLI
🔧
Ansible DevOps & CLI
Helm DevOps & CLI
🔨
Jenkins DevOps & CLI
🔥
Prometheus DevOps & CLI
📊
Grafana DevOps & CLI
💻
Zsh DevOps & CLI
🐟
Fish Shell DevOps & CLI
💙
PowerShell DevOps & CLI
🔄
Argo CD DevOps & CLI
🔀
Traefik DevOps & CLI
☁️
Azure CLI DevOps & CLI
☁️
Google Cloud CLI DevOps & CLI
📟
tmux DevOps & CLI
🔧
jq DevOps & CLI
✂️
sed DevOps & CLI
📊
awk DevOps & CLI
🌊
Apache Airflow DevOps & CLI
🔢
NumPy 데이터베이스 & 데이터
🐼
Pandas 데이터베이스 & 데이터
🔥
PyTorch 데이터베이스 & 데이터
🧠
TensorFlow 데이터베이스 & 데이터
📈
Matplotlib 데이터베이스 & 데이터
🐘
PostgreSQL 데이터베이스 & 데이터
🐬
MySQL 데이터베이스 & 데이터
🍃
MongoDB 데이터베이스 & 데이터
🔴
Redis 데이터베이스 & 데이터
🔍
Elasticsearch 데이터베이스 & 데이터
🤖
Scikit-learn 데이터베이스 & 데이터
👁️
OpenCV 데이터베이스 & 데이터
Apache Spark 데이터베이스 & 데이터
🪶
SQLite 데이터베이스 & 데이터
Supabase 데이터베이스 & 데이터
🔵
Neo4j 데이터베이스 & 데이터
📨
Apache Kafka 데이터베이스 & 데이터
🐰
RabbitMQ 데이터베이스 & 데이터
🔤
Regex 유틸리티
📝
Markdown 유틸리티
📄
LaTeX 유틸리티
🔐
SSH & GPG 유틸리티
🌐
curl & HTTP 유틸리티
📜
reStructuredText 유틸리티
🚀
Postman 유틸리티
🎬
FFmpeg 유틸리티
🖼️
ImageMagick 유틸리티
🔍
ripgrep 유틸리티
🔍
fzf 유틸리티
📗
Microsoft Excel 오피스 애플리케이션
📘
Microsoft Word 오피스 애플리케이션
📙
Microsoft PowerPoint 오피스 애플리케이션
📝
한컴 한글 한컴오피스
📽️
한컴 한쇼 한컴오피스
📊
한컴 한셀 한컴오피스
📄
Google 문서 Google Workspace
📊
Google 스프레드시트 Google Workspace
📽️
Google 프레젠테이션 Google Workspace
🔌
Cadence Virtuoso EDA & 하드웨어
⚙️
Synopsys EDA EDA & 하드웨어
💎
Verilog & VHDL EDA & 하드웨어
LTSpice EDA & 하드웨어
🔧
KiCad EDA & 하드웨어
📝
Notion 생산성 도구
💎
Obsidian 생산성 도구
💬
Slack 생산성 도구
🎮
Discord 생산성 도구
🎨
Figma 디자인 도구
📘
Confluence Atlassian
📋
Jira Atlassian
🃏
Jest 테스팅
Vitest 테스팅
🎭
Playwright 테스팅
🌲
Cypress 테스팅
🌐
Selenium 테스팅
💙
Flutter 모바일 개발
📱
React Native 모바일 개발
🍎
SwiftUI 모바일 개발
📱
Expo 모바일 개발
🐍
Django 웹 프레임워크
FastAPI 웹 프레임워크
🌶️
Flask 웹 프레임워크
🍃
Spring Boot 웹 프레임워크
🍸
Gin 웹 프레임워크
Vite 빌드 도구
📦
Webpack 빌드 도구
esbuild 빌드 도구
🐘
Gradle 빌드 도구
🪶
Maven 빌드 도구
🔧
CMake 빌드 도구
🎮
Unity 게임 개발
🤖
Godot 게임 개발
🔌
Arduino 임베디드 & IoT
🔍
Nmap 보안
🐕
Datadog 모니터링
📖
Swagger/OpenAPI 문서화
검색 결과가 없습니다
EN KO

CLI 명령어

프로젝트

npm i -g @nestjs/cli CLI 전역 설치
nest new project-name 새 프로젝트 생성
nest start 애플리케이션 시작
nest start --watch 핫 리로드로 시작
nest build 애플리케이션 빌드

생성

nest g module users 모듈 생성
nest g controller users 컨트롤러 생성
nest g service users 서비스 생성
nest g resource users CRUD 리소스 생성
nest g middleware logger 미들웨어 생성
nest g guard auth 가드 생성
nest g interceptor logging 인터셉터 생성
nest g pipe validation 파이프 생성
nest g filter http-exception 예외 필터 생성

기본 개념

모듈

기본 모듈
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
  imports: [],
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService],
})
export class UsersModule {}
글로벌 모듈
@Global()
@Module({
  providers: [ConfigService],
  exports: [ConfigService],
})
export class ConfigModule {}
동적 모듈
@Module({})
export class DatabaseModule {
  static forRoot(options: DbOptions): DynamicModule {
    return {
      module: DatabaseModule,
      providers: [
        {
          provide: 'DB_OPTIONS',
          useValue: options,
        },
        DatabaseService,
      ],
      exports: [DatabaseService],
    };
  }
}

컨트롤러

기본 컨트롤러
import { Controller, Get, Post, Body, Param, Query } from '@nestjs/common';

@Controller('users')
export class UsersController {
  constructor(private usersService: UsersService) {}

  @Get()
  findAll(@Query('limit') limit: number) {
    return this.usersService.findAll(limit);
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.usersService.findOne(id);
  }

  @Post()
  create(@Body() createUserDto: CreateUserDto) {
    return this.usersService.create(createUserDto);
  }
}
HTTP 메서드
@Get()        // GET /users
@Post()       // POST /users
@Put(':id')   // PUT /users/:id
@Patch(':id') // PATCH /users/:id
@Delete(':id')// DELETE /users/:id
@All()        // All methods

@HttpCode(204) // Set status code
@Header('Cache-Control', 'none') // Set header
@Redirect('https://nestjs.com', 301) // Redirect
요청 객체
@Get()
findAll(
  @Req() request: Request,
  @Res() response: Response,
  @Headers('authorization') auth: string,
  @Ip() ip: string,
  @HostParam() hosts: Record<string, string>,
) {}

서비스

기본 서비스
import { Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  private users = [];

  findAll(limit?: number) {
    return limit ? this.users.slice(0, limit) : this.users;
  }

  findOne(id: string) {
    return this.users.find(user => user.id === id);
  }

  create(createUserDto: CreateUserDto) {
    const user = { id: Date.now(), ...createUserDto };
    this.users.push(user);
    return user;
  }
}

미들웨어 및 파이프

미들웨어

미들웨어 생성
import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`${req.method} ${req.url}`);
    next();
  }
}
미들웨어 적용
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';

@Module({ ... })
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .exclude({ path: 'health', method: RequestMethod.GET })
      .forRoutes(UsersController);
  }
}

파이프

내장 파이프
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
  return this.usersService.findOne(id);
}

// Built-in pipes:
// ParseIntPipe, ParseBoolPipe, ParseArrayPipe
// ParseUUIDPipe, ParseEnumPipe, DefaultValuePipe
// ValidationPipe, ParseFloatPipe
커스텀 파이프
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';

@Injectable()
export class ParseIntPipe implements PipeTransform<string, number> {
  transform(value: string, metadata: ArgumentMetadata): number {
    const val = parseInt(value, 10);
    if (isNaN(val)) {
      throw new BadRequestException('Validation failed');
    }
    return val;
  }
}
유효성 검사 파이프
// main.ts
app.useGlobalPipes(new ValidationPipe({
  whitelist: true,
  forbidNonWhitelisted: true,
  transform: true,
}));

// dto
import { IsString, IsEmail, MinLength } from 'class-validator';

export class CreateUserDto {
  @IsString()
  @MinLength(2)
  name: string;

  @IsEmail()
  email: string;
}

가드 및 인터셉터

가드

인증 가드
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return this.validateRequest(request);
  }

  private validateRequest(request: any): boolean {
    return !!request.headers.authorization;
  }
}
가드 적용
// Controller level
@UseGuards(AuthGuard)
@Controller('users')
export class UsersController {}

// Method level
@UseGuards(AuthGuard)
@Get()
findAll() {}

// Global
app.useGlobalGuards(new AuthGuard());
역할 기반 가드
import { SetMetadata } from '@nestjs/common';
export const Roles = (...roles: string[]) => SetMetadata('roles', roles);

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!roles) return true;
    const request = context.switchToHttp().getRequest();
    const user = request.user;
    return roles.some(role => user.roles?.includes(role));
  }
}

// Usage
@Roles('admin')
@UseGuards(AuthGuard, RolesGuard)
@Get('admin')
adminRoute() {}

인터셉터

로깅 인터셉터
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const now = Date.now();
    return next
      .handle()
      .pipe(
        tap(() => console.log(`After... ${Date.now() - now}ms`)),
      );
  }
}
변환 인터셉터
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
    return next.handle().pipe(
      map(data => ({ data, statusCode: 200, timestamp: new Date().toISOString() })),
    );
  }
}

예외 처리

예외

내장 예외
throw new BadRequestException('Invalid data');
throw new UnauthorizedException('Please login');
throw new NotFoundException('User not found');
throw new ForbiddenException('Access denied');
throw new ConflictException('Already exists');
throw new InternalServerErrorException();
throw new HttpException('Custom error', HttpStatus.BAD_REQUEST);
예외 필터
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: exception.message,
    });
  }
}

// Apply
@UseFilters(HttpExceptionFilter)
@Controller('users')
export class UsersController {}

데이터베이스

TypeORM

설정
// app.module.ts
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'user',
      password: 'password',
      database: 'mydb',
      entities: [User],
      synchronize: true, // dev only
    }),
  ],
})
export class AppModule {}
엔티티
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column({ unique: true })
  email: string;

  @CreateDateColumn()
  createdAt: Date;
}
레포지토리
// users.module.ts
@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [UsersService],
})
export class UsersModule {}

// users.service.ts
@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  findAll(): Promise<User[]> {
    return this.usersRepository.find();
  }

  findOne(id: number): Promise<User> {
    return this.usersRepository.findOneBy({ id });
  }

  create(dto: CreateUserDto): Promise<User> {
    const user = this.usersRepository.create(dto);
    return this.usersRepository.save(user);
  }
}