Nest.js
[m1 맥북] - nest.js 공부하기 6. 게시물 생성하기
Dev갱이
2022. 4. 27. 00:09
728x90
게시물 생성 기능 만들기
게시물에 관한 로직을 처리하는 곳은 Service입니다. 그래서 먼저 Service에서 로직을 처리해준 후에 Controller에서 서비스를 불러와주겠습니다.
Service -> Controller
//service
import { Injectable } from '@nestjs/common';
import { Board, BoardStatus } from './board.model';
@Injectable()
export class BoardsService {
private boards: Board[] = []; //private 사용하는 이유는 클래스 내에서만 접근해서 수정 가능하게 하려고.
getAllBoards(): Board[]{ //리턴값 타입지정
return this.boards;
}
createBoard(title: string, description: string) {
const board: Board = {
title : title,
description: description,
status: BoardStatus.PUBLIC
}
}
}

게시물의 id값이 없어서 오류가 발생되는 모습이다.
게시물의 ID는 모든 게시물에 유니크 해야한다. 그래서 유니크한 값을 위해 uuid 모듈을 이용해서 유니크한 값을 준다.
uuid 모듈 설치
npm install uuid --save
//service
import { Injectable } from '@nestjs/common';
import { Board, BoardStatus } from './board.model';
import { v1 as uuid } from 'uuid';
@Injectable()
export class BoardsService {
private boards: Board[] = []; //private 사용하는 이유는 클래스 내에서만 접근해서 수정 가능하게 하려고.
getAllBoards(): Board[]{ //리턴값 타입지정
return this.boards;
}
createBoard(title: string, description: string) {
const board: Board = {
id : uuid(),
title : title,
description: description,
status: BoardStatus.PUBLIC
}
this.boards.push(board);
return board;
}
}
Controller에서 Service로직을 불러온다.
request와 response 부분 처리는 Controller 에서 해주면 됩니다.

//controller
import { Body, Controller, Get, Post } from '@nestjs/common';
import { Board } from './board.model';
import { BoardsService } from './boards.service';
@Controller('boards')
export class BoardsController {
constructor(private boardsService : BoardsService){}
@Get('/')
getAllBoard(): Board[] {
return this.boardsService.getAllBoards();
}
@Post()
createBoard(
@Body('title') title : string,
@Body('description') description : string
): Board {
return this.boardsService.createBoard(title, description);
}
}
NestJS에서는 @Body body를 이용해서 가져옵니다.
이렇게 하면 모든 request에서 보내온 값을 가져올 수 있으며, 하나씩 가져오려면 @Body('title') title:string 이런식으로 가져오면 된다.
//한번에 가져올때
@Post()
createBoard(@Body() body){
console.log('body',body);
}
@Post()
createBoard(
@Body('title') title: string,
@Body('descriptiopn') description: string,
){
console.log(title);
console.log(description);
}
728x90