nestJS 기초

정윤수·2022년 1월 25일
0

nestJS 시작

  • npm 안정된 버전(왼쪽) 설치 후,
mkdir nestjs-test-app
cd nestjs-test-app
npm install -g @nestjs/cli
nest new ./

nestJS 기본 구조

  • .eslintrc.js : 개발자들이 특정한 규칙을 가지고 코드를 깔끔하게 짤 수 있게 도와 주는 라이브러리, 타입 스크립트를 쓰는 가이드 라인 제시, 문법에 오류가 나면 알려주는 역할을 한다. 주로, 문법 오류나면 알려주는 역할
  • .prettierrc : 주로 코드 형식을 맞추는데 사용한다. 작은 따옴표(’)를 사용할지 큰 타옴표(”)를 사용할지, Indent 값을 2로 줄지, 4로 줄지 등등, 에러 찾는 것이 아닌 코드 포멧터 역할을 한다. 주로, 코드 포멧터 역할 (협업끼리 미리 정하는 코드 약속
  • nest-cli.json : nestjs프로젝트 자체에 필요한 설정들
  • tsconfig.json : 어떻게 타입스크립트를 컴파일 할지 설정

nestJS의 HelloWorld! 구조

  • src/main.ts 가 nestjs의 시작점
  • main - Controller - service(에서 대부분 처리)

<main.ts>

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);   //모듈 실행
  await app.listen(3000);
}
bootstrap();

<app.module.ts>

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],     //해당 모듈에서는 컨트롤러 실행
  providers: [AppService],
})
export class AppModule {}

<app.controller.ts>

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();    //get메소드로 getHello() 실행
  }                                       //appService하위의 getHello 실행
}

<app.service.ts>

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

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';          //appService는 getHello 실행 할 땐,       
		}                               //'Hello World!'를 return
}

App모듈 안

보드모듈 인증모듈 (각 모듈 당, 컨트롤러, 서비스, 엔터티 등등 을 가지는 구조)

실행 순서

브라우저에서 요청(req) → controller에서 알맞은 요청경로에 따라서, 그에 따른 요청처리해줘서 다시 브라우저에 요청처리해주는 것 (서비스는 controller의 도구일뿐)

nest g module boards        //boards라는 모듈 생성
nest g controller boards --no-spec   //boards라는 컨트롤러 생성
nest g service boards --no-spec //boards라는 서비스 생성
  • Injecte : 주입할 수 있다, —no-sepc: 테스트 코드 없이
  • Board Service에서 Injectable 데코레이터 덕분에 NestJS에서 이를 이용해서 다른 컴포넌트에서(전체 앱에서) 이 Service를 사용할 수 있게(Injectable)만들어준다. (@Injectable로 감싸주면 가능)

CRUD

1. R

@Controller('boards')
export class BoardsController {
		//boardsService: BoardsService  //private 적어줌으로써 ⇒ 암묵적으로 property라고 사용가능
    constructor(private boardsService: BoardsService) {}
		//BoardsService란 타입으로 boardsService라는 property에 넣어서
    getAllTask() {
        this.boardsService. //위 property를 service에접근하여, service안 메서드를 가져와서 쓸 수 있는 것!
    }
}

C 하기 전 타입 지정

model : 게시물에 필요한 데이터가 어떤거 어떤거인지 미리 적어주기 위해서 게시물의 모델을 만들어준다. ex) 게시물 모델 : id, 이름, 설명이 담기는 곳

/boards 하위에 /board.model.ts라는 파일 생성

model 정의하는 법 ⇒

  • class (변수 타입만 체크)
  • interface (변수 타입 체크와인스턴스 동시에 생성 가능)

<board.model.ts>

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

export enum BoardStatus {
    PUBLIC = 'PUBLIC',
    PRIVATE = 'PRIVATE'
}

2. C

<boards.service.ts>

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

@Injectable()
export class BoardsService {
    private boards: Board[] = []; //boards 타입 지정
    
    getAllBoards(): Board[] { // 리턴값 타입 지정도 가능
        return this.boards;
    }

    createBoard(title: string, description: string) {
        const board: Board = {
            id: uuid(),
            title,
            description,
            status: BoardStatus.PUBLIC
        }
        
        this.boards.push(board);
        return board;
        
    }
}

<boards.controller.ts>

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

@Controller('boards')
export class BoardsController {
    constructor(private boardsService: BoardsService) {}
    
    @Get('/')
    getAllBoard(): Board[] {
        return this.boardsService.getAllBoards();
    }

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

++ DTO

데이터 유효성 체크에 효율적, 안정적 코드 생성 가능

@Body 에서 불러오는 property가 많아질수록 나중에 하나 지우는 데에도 여러 군데를 찾아 지우느라 시간 많이 잡아먹음 ⇒ DTO로 해결

런타임 ? 프로그램이 실행되고있는 중에

/src/board 밑에 /dto 폴더 생성
/dto/create-board.dto.ts 파일 생성 

<create-board.dto.ts>

export class CreateBoardDto {
    title: string;
    description: string;
}

<board.controller.ts>

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

@Controller('boards')
export class BoardsController{
    constructor(private boardsService: BoardsService){}
    
    @Get()
    getAllBoard(): Board[]{
        return this.boardsService.getAllBoards();
    }

    @Post()
    createBoard(
        @Body() createBoardDto: CreateBoardDto) {
    return this.boardsService.createBoard(createBoardDto);
        
    }

}

<board.service.ts>

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

@Injectable()
export class BoardsService {
    private boards: Board[] = [];  //가상 DB
    
    getAllBoards(): Board[]{
        return this.boards;
    }

    createBoard(createBoardDto: CreateBoardDto){
        const { title, description } = createBoardDto;
        const board ={
            id: uuid(),
            title,
            description,
            status: BoardStatus.PUBLIC,
        }

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

}

R, D, U

<boards.controller.ts>

import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
import { Board, BoardStatus } from './boards.model';
import { BoardsService } from './boards.service';
import { CreateBoardDto } from './dto/create-board.dto';

@Controller('boards')
export class BoardsController{
    constructor(private boardsService: BoardsService){}
    
    @Get()
    getAllBoard(): Board[]{
        return this.boardsService.getAllBoards();
    }

    @Post()
    createBoard(
        @Body() createBoardDto: CreateBoardDto): Board {
            return this.boardsService.createBoard(createBoardDto);
    }

    @Post('/:id')       //특정 id로 특정게시물 가져오기 
    getBoardById(
        @Param('id') id: string): Board {
            return this.boardsService.getBoardById(id);
    }

    @Delete('/:id')     //특정 id로 특정게시물 지우기
    deleteBoardById(
        @Param('id') id:string): void {
            return this.boardsService.deleteBoardById(id);
        }
    
    @Patch('/:id')
    UpdateBoardStatus(
        @Param('id') id: string,
        @Body('status') status: BoardStatus): Board {
            return this.boardsService.updateBoardStatus(id, status);
    }

}

<boards.service.ts>

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

@Injectable()
export class BoardsService {
    private boards: Board[] = [];  //가상 DB
    
    getAllBoards(): Board[]{
        return this.boards;
    }

    createBoard(createBoardDto: CreateBoardDto){
        const { title, description } = createBoardDto;
        const board ={
            id: uuid(),
            title,
            description,
            status: BoardStatus.PUBLIC,
        }

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

    getBoardById(id: string){
        return this.boards.find((board)=> board.id === id);
    }
    
    deleteBoardById(id: string): void{
        this.boards = this.boards.filter((board)=> board.id !== id)
        //해당 id와 같지않은 아이디만 boards에 남도록 = 해주는 것
    }

    updateBoardStatus(id: string, status: BoardStatus){
        const board = this.getBoardById(id);
        board.status = status;
        return board;
    }

}

// react, nestjs (Fullstack API Tutorial #1 NodeJs, NestJs, React, TypeORM & TypeScript - YouTube)

profile
https://www.youtube.com/watch?v=whoDs0KRc7k&t=1s

0개의 댓글

관련 채용 정보