Frontend/Nest.js

NestJS : 라우터 및 데코레이터 설명

wam 2023. 1. 9. 16:38

 

Single Responsibility Principle 따르자

하나의 module, class 혹은 function이 하나의 기능은 꼭 책임야 한다.

하나의 module, class 혹은 function이 하나의 기능은 꼭 책임져야 한다. 객체 지향 프로그래밍에서 단일 책임 원칙(single responsibility principle)이란 모든 클래스는 하나의 책임만 가지며, 클래스는 그 책임을 완전히 캡슐화해야 함을 일컫는다. 클래스가 제공하는 모든 기능은 이 책임과 주의 깊게 부합해야 한다.   _출처: 위키백과

 

 


 

  • decorator에서 뭔가를 원한다면 요청을 해야 한다.
  • parameter 필요하면 직접 요청해야 한다.
  • body 가 필요하면 직접 요청해야 한다.

 

  • ExpressJs에서 body를 json으로 리턴하려면 설정을 해줘야 했다.
  • NestJs에서는 json으로 바로 받을 수 있다.

 

 


 

컨트롤러 추가 "movies"

// src/movies/movies.controller.ts

import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Patch,
  Post,
  Query,
} from '@nestjs/common';
import { Movie } from './entities/movie.entity';
import { MoviesService } from './movies.service';

@Controller('movies')
export class MoviesController {
  constructor(private readonly moviesService: MoviesService) {}

  @Get()
  getAll(): Movie[] {
    return this.moviesService.getAll();
  }

  @Get('/:id')
  getOne(@Param('id') movieId: string) {
    return this.moviesService.getOne(movieId);
  }

  @Post()
  create(@Body() movieData) {
    return this.moviesService.create(movieData);
  }

  @Delete('/:id')
  remove(@Param('id') movieId: string) {
    return this.moviesService.deleteOne(movieId);
  }

  @Patch('/:id')
  patch(@Param('id') movieId: string, @Body() updateData) {
    return this.moviesService.update(movieId, updateData);
  }
}

 

@Controller('movies')

  • Controller의 이름값으로 URL이 만들어진다.
  • http://localhost:3000/movies
  • Controller의 이름 부분은 URL의 Entry Point(엔트리 포인트)를 컨트롤한다.
  • express.js 애플리케이션을 쓸 때의 라우터와 같다.

 

 

URL의 파라미터 값을 얻을 때

  @Get('/:id')
  getOne(@Param('id') movieId: string) {
    return this.moviesService.getOne(movieId);
  }
  • 예를 들어, getOne()에서 요청하는 방법은 파라미터를 요청하는 것이다.
  • 파라미터의 decorator를 사용한다면 NestJS는 URL에 있는 id 파라미터를 원하는 것을 알 수 있게 된다.
  • id라는 파라미터를 movieId라는 argument에 string 타입으로 저장한 것

 

  • 라우터의 @Get('/:id')와 @Param('id') 이름이 같아야 한다.
  • @Param('id')와 파라미터의 argument인 movieId: string는 이름이 달라도 된다. 

 

 

Update 데코레이터 (Put, Patch)

  @Patch('/:id')
  patch(@Param('id') movieId: string, @Body() updateData) {
    return this.moviesService.update(movieId, updateData);
  }
  • 전체 movie를 업데이트할 때 = Put 사용
  • movie의 일부분만 업데이트할 때는 patch 사용

 

 

@Post에서 request의 body 부분을 가져오고 싶을 때

    @Post()
    create(@Body() movieData) {
        console.log(movieData)
    	return this.moviesService.create(movieData);
    }
  • Body 내용을 가져올 때 @Body 데코레이터를 사용하면 된다.

 

 

Query 데코레이터 사용하기

    @Get('search')
    search(@Query('year') searchingYear: string){
        return `We are searching for a movie made after: ${searchingYear}`;
    }
  • 예를 들면 2000년 이후에 movie 만 가져오고 싶을 때 name 같은 query argument를 보내보기
  • http://localhost:3000/movies/search?year=2000


 [위치 주의] search 부분이 get(:id) 보다 밑에 있으면 NestJS는 search를 id로 판단한다.

// [잘못된 위치] (:id) 보다 아래 있으면 안된다.

src/movies/movies.controller.ts

import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';

@Controller('movies')
export class MoviesController {
    @Get()
    getAll(){
        return 'This will return all movies';
    }

    @Get('/:id')
    getOne(@Param('id') movieId: string){
        return `This will return one movie with the id: ${movieId}`;
    }

    @Get('search') // 여기에 위치하면 안된다!
    search(){
        return 'We are searching for a movie with a title: ';
    }
}
// [정확한 위치] (:id) 보다 위에 있어야 한다.

src/movies/movies.controller.ts

import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';

@Controller('movies')
export class MoviesController {
    @Get()
    getAll(){
        return 'This will return all movies';
    }

    @Get('search') // 여기에 위치하면 된다!
    search(){
        return 'We are searching for a movie with a title: ';
    }

    @Get('/:id')
    getOne(@Param('id') movieId: string){
        return `This will return one movie with the id: ${movieId}`;
    }
}