JS/Nest.js

[Nest JS] 설정 ~ 게시글 생성

Mini_96 2024. 8. 17. 15:41

* 출처

https://www.youtube.com/watch?v=3JminDpCJNE&list=PL9a7QRYt5fqmxPccmnDTUXWeyKm4h2lHl

 

* 프로젝트 생성

npm install -g @nest/cli

이후 폴더에서 new new ./

* 기본구조

 

* 인텔리제이에서 ts 실행방법

플러그인 설치후 적용하면 된다
이후 > 버튼 딸깍으로 실행 가능하다.

 

* 서비스 요청 흐름도

'/' 에 맞는 컨트롤러 실행 -> 서비스 실행 -> 응답 리턴
응답

 

* 게시판 모듈 구현

자동 import 등 해줌

* 컨트롤러 구현

- 명령어 : nest g controller boards --no-spec

 

* Provider, Service 란?

Spring의 DI와 비슷한것 같다.

컨트롤러는 서비스, 리포지토리등을 사용함. 

연결(의존성 주입)은 Provider에 위임

 

즉, @Injectable()로 감싸줘야 관리대상이됨 => 해당 서비스를 컨트롤러에 주입가능.

또, 등록할 서비스를 module에 등록해줘야함.

 

* service 구현

서비스에서는 db 관련 로직을 주로 처리함.

명령어 : nest g service boards --no-spec

자동으로 provider도 업데이트 해줌
@Injectable => 어디에서든(컨트롤러) 이 서비스를 사용가능

 

* 의존성주입

컨트롤러에서 사용할 서비스의 인스턴스를 만드는것임.

간단하게 1줄로 바꿀수 있음.

위2개는 같은 코드임.

import { Controller } from '@nestjs/common';
import { BoardsService } from "./boards.service";

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

 

* 모두조회 서비스 구현

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

  getAllBoards(){
    return this.boards;
  }
}

컨트롤러에서 서비스를 사용

@Controller 뒤의 매개변수는 prefix임.

@Get 안의 매개변수는 prefix 뒤에 붙는 url임

import { Controller, Get } from "@nestjs/common";
import { BoardsService } from "./boards.service";

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

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

이경우는 localhost:3000/boards/ 요청을 처리함.

결과

 

* 모델 구현

for 명세서

 

* enum => 값 제한

export interface Board{
  id: string;
  title : string;
  description : string;
  status : BoardStatus; //private or public 만 올 수 있음
}

//enum => 값 제한
export enum BoardStatus{
  PUBLIC = 'PUBLIC',
  PRIVATE = 'PRIVATE'
}

- 서비스에서 타입지정

import { Injectable } from '@nestjs/common';
import { Board } from "./board.model";

@Injectable()
export class BoardsService {
  private boards : Board[] = []; //memory repository

  getAllBoards() : Board[]{
    return this.boards;
  }
}

- 컨트롤러에서도 리턴 타입지정

import { Controller, Get } from "@nestjs/common";
import { BoardsService } from "./boards.service";
import { Board } from "./board.model";

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

  @Get()
  getAllBoards() : Board[]{
    return this.boardsService.getAllBoards();
  }
}

 

* 게시글 생성 구현

@Injectable()
export class BoardsService {
  private boards : Board[] = []; //memory repository

  getAllBoards() : Board[]{
    return this.boards;
  }

  createBoard(title : string, description : string){
    const board = {
      title,
      description,
      status : BoardStatus.PUBLIC
    }
  }

 

문제 : id가 들어가야함 -> 실제 db에서는 자동으로 넣어줌 -> 메모리에서는 uuid 모듈사용

npm install uuid --save
import {v1 as uuid} from 'uuid';
createBoard(title : string, description : string){
  const board = {
    id : uuid(), //자동으로 유니크한 값을 넣어줌
createBoard(title : string, description : string){
  const board = {
    id : uuid(),  //자동으로 유니크한 값을 넣어줌
    title,
    description,
    status : BoardStatus.PUBLIC
  }

  this.boards.push(board);
  return board;
}

* 클라에서 데이터 받는 방법

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

 ...

  //생성은 post
  @Post()
  createBoard(    @Body('title') title:string,    @Body('description') description:string, ) : Board{
    return this.boardsService.createBoard(title,description);
  }

매개변수안에 Body로 클라의 데이터를 받아옴.

JSON 타입으로 보내야 작동함.