클라이언트에서 요청을 보내면 컨트롤러로 가며 컨트롤러에서 알맞은 요청 경로에 라우팅하여 해당 핸들러로 가게 해줌. 그 이후 요청을 처리하기 위해 서비스로 잉동하여 로직을 처리한 후 컨트롤러에서 클라이언트로 결과값을 보내줌.
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();
}
}
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)
}
계층간 데이터 교환을 위한 객체
DB에서 데이터를 얻어 서비스나 컨트롤러 등으로 보낼 때 사용하는 객체.
interface나 class를 이용해 정의될 수 있음.(class 추천)
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;
}
@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;
}