NestJS

MONA·2025년 8월 4일

나혼공

목록 보기
88/92

NestJS

TypeScript 기반 백엔드 프레임워크
모듈화, 의존성주입, 데코레이터 기반 아키텍처를 제공하여 대규모 애플리케이션을 설계하기 유지보수하기 쉽게 해줌

특징

  • TypeScript 기반
  • 모듈화 구조
  • 의존성 주입
  • Express or Fastfy 기반

핵심 개념

Module

  • NestJS의 기본 구성 단위
  • 관련 기능들을 하나의 모듈로 묶음

Controller

  • 라우팅 담당 (HTTP 요청 -> 응답)

Service(Provider)

  • 비즈니스 로직 담당
  • DI(의존성 주입)을 통해 Controller에서 사용

Dependency Injection

  • constructor(private readonly service: Myservice) {} 구조로 서비스 주입

개발환경 구성

# Homebrew로 nvm 설치
brew install nvm

# nvm 디렉토리 생성
mkdir ~/.nvm

# zsh 설정파일에 추가
echo 'export NVM_DIR="$HOME/.nvm"' >> ~/.zshrc
echo '[ -s "/opt/homebrew/opt/nvm/nvm.sh" ] && \. "/opt/homebrew/opt/nvm/nvm.sh"' >> ~/.zshrc
source ~/.zshrc

# Node 설치 및 NestJS CLI 설치
nvm install --lts
npm install -g @nestjs/cli

실습하기

# 프로젝트 생성
nest new nest-practice

# 프로젝트 디렉토리로 이동
cd nest-practice

# 모듈, 컨트롤러, 서비스 생성
nest generate resource posts
  • REST API -> Y
  • CRUD entry points -> Y
src/posts/
  ├── dto/
  │    ├── create-post.dto.ts
  │    └── update-post.dto.ts
  ├── entities/
  │    └── post.entity.ts
  ├── posts.controller.ts
  ├── posts.service.ts
  └── posts.module.ts

위와 같은 구조로 posts 가 생성된다.

기본 생성된 dto를 제목과 내용을 받을 수 있게 수정해주었다.

export class CreatePostDto {
  title: string;
  content: string;
}
import { PartialType } from '@nestjs/mapped-types';
import { CreatePostDto } from './create-post.dto';

export class UpdatePostDto extends PartialType(CreatePostDto) {}

controller는 생성된 그대로 사용하고, service 코드도 맞춰서 수정해준다.

import { Injectable } from '@nestjs/common';
import { Post } from './entities/post.entity';
import { CreatePostDto } from './dto/create-post.dto';
import { UpdatePostDto } from './dto/update-post.dto';

@Injectable()
export class PostsService {
  private posts: Post[] = [];
  private idCounter = 1;

  create(createPostDto: CreatePostDto): Post {
    const newPost: Post = {
      id: this.idCounter++,
      ...createPostDto,
    };
    this.posts.push(newPost);
    return newPost;
  }

  findAll(): Post[] {
    return this.posts;
  }

  findOne(id: number): Post | undefined {
    return this.posts.find((post) => post.id === id);
  }

  update(id: number, updatePostDto: UpdatePostDto): Post | null {
    const post = this.findOne(id);
    if (!post) return null;

    Object.assign(post, updatePostDto);
    return post;
  }

  remove(id: number): void {
    this.posts = this.posts.filter((post) => post.id !== id);
  }
}

그리고 실행하는데, controller에서 모든 데코레이터에 에러가 발생하는 것을 확인했다.
main.ts 최상단에 import 'reflect-metadata';가 없어서 발생한 에러였다.
추가하고 저장해주니 에러가 싹 사라졌다.

postman으로 확인해보니 정상 실행되었다.

typescript를 써 본 감상으로는.. 저장이 너무 빡세다. 저장 한 번 안하면 그냥 내용이 반영이 안된다.
넘나 귀찮은것...

profile
고민고민고민

0개의 댓글