Nest.js CRUD

김민석·2026년 3월 11일
post-thumbnail

요청 및 응답 구조 이해

클라이언트에서 요청을 보내면 컨트롤러로 가며 컨트롤러에서 알맞은 요청 경로에 라우팅하여 해당 핸들러로 가게 해줌. 그 이후 요청을 처리하기 위해 서비스로 잉동하여 로직을 처리한 후 컨트롤러에서 클라이언트로 결과값을 보내줌.

모든 boards 불러오기

import { Injectable } from '@nestjs/common';

@Injectable()
export class BoardsService {
  private boards = [];

  getAllBoards() {
    return this.boards;
  }
}
import { Controller, Get } from '@nestjs/common';
import { BoardsService } from './boards.service';

@Controller('boards')
export class BoardsController {
  constructor(private readonly boardsService: BoardsService) {

  }
  @Get("/")
  async getAllBoards() {
    return this.boardsService.getAllBoards();
  }

}

모델 생성

  • interface : 변수의 타입만 체크
  • classes : 타입 체크 및 인스턴스 생성
export enum BoardStatus {
  PUBLIC = 'PUBLIC',
  PRIVATE = 'PRIVATE'
}

export interface Board {
  id: string;
  title: string;
  description: string;
  status: BoardStatus;
}

게시물 생성

createBoard(title: string, description: string) {
    const board: Board = {
      id: uuidv4(),
      title,
      description,
      status: BoardStatus.PUBLIC
    }
    this.boards.push(board);
    return board;
  }
 @Post()
  createBoard(@Body('title') title: string, @Body('description') description: string): Board {
    return this.boardsService.createBoard(title, description)
  }

DTO(Data Transfer Object)

계층간 데이터 교환을 위한 객체
DB에서 데이터를 얻어 서비스나 컨트롤러 등으로 보낼 때 사용하는 객체.
interface나 class를 이용해 정의될 수 있음.(class 추천)

DTO 왜 쓰나

  • 데이터 유효성을 체크하는데 효율적
  • 안정적인 코드로 만들어줌
  • 프로퍼티가 많아질수록 복잡함. 또 여러곳에서 사용한다면 다 바꿔줘야함. 하나의 DTO를 만들면 DTO만 바꾸면됨. 유지보수 up

Create DTO 생성

export class CreateBoardDto {
  title: string;
  description: string;
}
@Post()
  createBoard(@Body() createBoardDto: CreateBoardDto): Board {
    return this.boardsService.createBoard(createBoardDto)
  }
createBoard(createBoardDto: CreateBoardDto): Board {
    const { title, description } = createBoardDto
    const board: Board = {
      id: uuidv4(),
      title,
      description,
      status: BoardStatus.PUBLIC
    }
    this.boards.push(board);
    return board;
  }

특정 id의 게시물 가져오기

 @Get("/:id")
  getBoardById(@Param("id") id: string): Board {
    return this.boardsService.getBoardById(id);
  }

params를 이용하여 id를 가져와 할거기 떄문에 @Param을 이용해 id르 가져와 service에 id를 보내줌. 받아온 id를 통해 boards에 같은 id가 있는지 찾은 후 보내준다.

getBoardById(id: string): Board {
    const board = this.boards.find(board => board.id === id);
    if (!board) {
      throw new NotFoundException(`Board with id ${id} not found`);
    }
    return board;
  }
profile
나만의 기록장

0개의 댓글