NestJS 배워보기

LeeJaeHoon·2021년 12월 4일
0
post-thumbnail
  1. Nestjs는 main.ts에서 모든 걸 시작한다.
    • 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();
    • AppModule
      • controller

        • url을 가져오고 함수를 실행시킨다.
        • express라우터와 같은 것이라고 보면된다.
      • @Module
        - 데코레이터라고 부른다 .
        - 데코레이터는 클래스에 함수 기능을 추가할 수 있다.

        import { Module } from '@nestjs/common';
        import { AppController } from './app.controller';
        import { AppService } from './app.service';
        
        @Module({
          //데코레이터라고 부른다 데코레이터는 클래스에 함수 기능을 추가할 수 있다.
          imports: [],
          controllers: [AppController], //url을 가져오고 함수를 실행시킨다. express라우터 같은것
          providers: [AppService],
        })
        export class AppModule {} //모든것의 루트 모듈
    • AppController
      • @Get("URL")
        - express의 get라우터와 같은역할을 한다
        - 해당 URL에 GET요청이 오면 바로밑의 함수를 실행 시킨다.

        import { Controller, Get } from '@nestjs/common';
        import { AppService } from './app.service';
        
        @Controller()
        export class AppController {
          constructor(private readonly appService: AppService) {}
        
          @Get() //express의 get라우터와 같은 역할
          getHello(): string {
            return this.appService.getHello();
          }
        
          @Get('/hello') //누군가가 /hello로 들어오면 sayHello라는 함수를 실행시킨다.
          sayHello(): string {
            return 'hello sveryone';
          }
        }
    • 위의 AppController에서 볼 수 있듯이 해당 URL의 함수를 바로 쓰기보다는 appService를 통해 구분해 놓는다.
      • NestJS는 컨트롤러를 비지니스 로직이랑 구분 짓고 싶어한다.
      • 컨트롤러는 그냥 url을 가져오는 역할일 뿐이다.
  2. movie Controller만들기
    • npx nest g co
      • 자동으로 movieController을 만들어준다.
    • movie.controller.ts
      • @Controller("movies")

        • movies라우터랑 같음 (localhost:3000/movies)
      • /:id에서 id가져오는 법

        • @Param("id")
      • 프론트엔드에서 보낸 JSON 가져오는법

        • @Body()
        • Nest에서는 JSON파일을 다시 프론트로 보낼때 따로 작업없이 바로 보낼 수 있다!
      • Query가져오는법 → localhost:3000/search?year=200
        - @Query("year")

        import {
          Controller,
          Get,
          Param,
          Post,
          Delete,
          Patch,
          Body,
          Query,
        } from '@nestjs/common';
        
        @Controller('movies') //movies라우터링 같음
        export class MoviesController {
          @Get()
          getAll() {
            return 'This will return all movies';
          }
        
          @Get('search')
          search(@Query('year') searchingYear: string) {
            return `we are searching for a movie made after: ${searchingYear}`;
          }
        
          @Get('/:id')
          getOne(@Param('id') movieId: string) {
            return `This will return one movie with the id: ${movieId}`;
          }
        
          @Post()
          create(@Body() movieData) {
            return movieData;
          }
        
          @Delete('/:id')
          remove(@Param('id') movieId: string) {
            return `this will delete a movie with the id: ${movieId}`;
          }
        
          @Patch('/:id')
          path(@Param('id') movieId: string, @Body() updateData) {
            return {
              updataeMovie: movieId,
              ...updateData,
            };
          }
        }
  3. Movie Service 만들기
    • npx nest g s
      • 자동으로 MoviesService을 만들어준다.
    • movie.service.ts
      import { Injectable } from '@nestjs/common';
      import { Movie } from './entities/movie.entity';
      
      @Injectable()
      export class MoviesService {
        private movies: Movie[] = []; //선언한 class내에서만 접근가능
      
        getAll(): Movie[] {
          return this.movies;
        }
      
        getOne(id: string): Movie {
          return this.movies.find((movie) => movie.id === +id);
        }
      
        deleteOne(id: string): boolean {
          this.movies.filter((movie) => movie.id !== +id);
          return true;
        }
      
        create(movieData) {
          this.movies.push({
            id: this.movies.length + 1,
            ...movieData,
          });
        }
      }
    • movie.controller.js
      import {
        Controller,
        Get,
        Param,
        Post,
        Delete,
        Patch,
        Body,
      } from '@nestjs/common';
      import { Movie } from './entities/movie.entity';
      import { MoviesService } from './movies.service';
      
      @Controller('movies') //movies라우터링 같음
      export class MoviesController {
        //매개변수 프로퍼티(Parameter Property) 를 이용하여 선언과 할당을 동시에 할 수 있습니다
        constructor(private readonly moviesService: MoviesService) {}
        @Get()
        getAll(): Movie[] {
          return this.moviesService.getAll();
        }
      
        @Post()
        create(@Body() movieData) {
          return this.moviesService.create(movieData);
        }
      
        @Get('/:id')
        getOne(@Param('id') movieId: string): Movie {
          return this.moviesService.getOne(movieId);
        }
      
        @Delete('/:id')
        remove(@Param('id') movieId: string): boolean {
          return this.moviesService.deleteOne(movieId);
        }
      
        @Patch('/:id')
        path(@Param('id') movieId: string, @Body() updateData) {
          return {
            updataeMovie: movieId,
            ...updateData,
          };
        }
      }
  4. 에러처리
    • throw new NotFoundException("에러내용");
      • nest에서 제공하는 NotFoundException을 통해 에러를 처리 할 수 있다.

        	getOne(id: string): Movie {
            const movie = this.movies.find((movie) => movie.id === +id);
            if (!movie) {
              throw new NotFoundException(`Movie with ID: ${id}`);
            }
            return movie;
          }

0개의 댓글