본문 바로가기
개발/프로젝트-식당 웨이팅 앱 FOOD LINE

230520 실전프로젝트2 [Node.js/Nest.js 환경 구축하기 1]

by 코딩하는짱구 2023. 5. 20.
반응형

✅오늘학습 Keyword

실전프로젝트를 nest 기반으로 진행하기 위해서 공부를 시작했다.

강의자료: https://www.youtube.com/watch?v=3JminDpCJNE&t=2s

 

👀NEST JS 란?

TypeScript로 구축된 프레임워크(Express.js를 기반으로 한 HTTP 서버 프레임워크)

**TypeScript는 JavaScript의 상위 집합 언어

  1. 모듈러 구조를 가지고 있어 독립적으로 개발되고 테스트 될 수 있다
  2. 라우팅, 미들웨어, 익셉션핸들링, 인증 등 다양한 기능 제공
  3. Dependency Injection이라는 디자인패턴을 사용하여 코드의 유지보수성과 테스트 용이성 향상 
  4. 대규모 애플리케이션의 개발에 적합하다

 

👀NEST JS 구조 파악하기

진입점app.module.ts(routes와 같은 역할)->controller->service->다시 return 해서 controller->출력

 

 

👀NEST JS 사용하기

  1. 프로젝트를 시작할 폴더를 생성
  2. 폴더안에서 nest 기본 구조 생성 npm i -g @nestjs/cli, nest new ./
  3. 앱실행 npm start:dev
  4. 모듈 생성 명령어: nest g module 모듈이름 
  5. test없이 controller 생성 명령어:  nest g controller 모듈이름 --no-spec
  6.  

7. 만들었으면 controller 안에  handler(get, post 등등)를 하나하나 만들어줘야한다. 

8. test없이 service 생성 명령어: nest g service 모듈이름 --no-spec

9. controller, service 다 만들었으면 controller에서 service를 사용할 수 있게 constructor로 의존성을 주입해준다. (dependency injection)

dependency injection

이렇게 원래는 선언한 값만 객체의 프로퍼티로 사용할 수 있기 때문에 코드가 3줄이여야 하지만 접근제한자를 이용해서 소스를 간단하게 만들 수 있다!

 

아래와 같이 controller에 service property를 설정해준다.

 

-게시글 작성, 조회부분 까지 완성된 API의 controller 부분 

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

//localhost:3000/boards<<경로주소
@Controller('boards')
export class BoardsController {
  constructor(private boardsService: BoardsService) {}

  @Get('/')
  //getAllBoard()라는 메서드 = BoardsController에서 /boards경로의 GET 요청을 핸들링하는 핸들러
  getAllBoards(): Board[] {
    return this.boardsService.getAllBoards();
  }

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

 

-게시글 작성, 조회부분 까지 완성된 API의 Service부분 

import { Injectable } from '@nestjs/common';
import { Board, BoardStatus } from './board.model';
import { v1 as uuid } from 'uuid';

//injectable 데코레이터
//해당 클래스가 주입가능한 서비스로 등록되어야 함을 알려준다.
@Injectable()
export class BoardsService {
  private boards: Board[] = [];

  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;
  }
}

 

✅오늘 겪은 문제 

1. 코드 형태(prettier)문제인지는 모르겠지만 계속 형태에 아래와같이 에러표시가 난다.     에러가 표기되지만 코드는 정상적으로 작동함.. prettier문제인지 뭔지 모르겠음..계속 공부하면서 알아내야 할듯 2. nest에서는 Controller, GET, POST API 뿐만 아니라 Body 까지 모두 @형태, 즉 데코레이터로 정의되기 때문에     반드시 @nestjs/common 에서 해당 모듈을 import해야한다. 방식이 익숙하지 않아서 빼먹어서 계속 아래와 같은 에러가 났음 .

 

src/boards/boards.controller.ts:16:4 - error TS2304: Cannot find name 'Post'. 16 @Post() ~~~~ src/boards/boards.controller.ts:18:6 - error TS2693: 'Body' only refers to a type, but is being used as a value here. 18 @Body('title') title: string, ~~~~ src/boards/boards.controller.ts:19:6 - error TS2693: 'Body' only refers to a type, but is being used as a value here. 19 @Body('description') description: string, ~~~~ [오후 2:25:35] Found 3 errors. Watching for file changes. 에러

 

✅오늘 알게된 점

nest 는 express에서 3계층 아키텍쳐와 유사한 구조를 가지고 있어서 구조를 이해하기에 편했다. 

반응형