컨트롤러란?
node.js
에서 쓰던 express.js
의 controller/router
같은 존재- client가 url로 접근한다면
- 요청받은 url을 가져오고,
- 이에 대응하는 서비스로부터 함수를 가져와서 실행한다.
예시
get 데코레이터
(@Get
)- express의 get 라우터같은 녀석임
데코레이터는 꾸며주는 함수나 클래스랑 붙어있어야 한다.
따라서 데코레이터랑 함수 사이에 빈칸을 두면 안됨 ㅇㅋ?
import { Controller, Get } from '@nestjs/common'; import { AppService } from './app.service'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} // 뒤에 추가 경로 없이 localhost:3000 으로 접속 시에 getHello()를 반환함 @Get() getHello(): string { return this.appService.getHello(); } // localhost:3000/hello로 진입 시 sayHello()를 반환함 @Get('/hello') sayHello(): string { return 'hello'; } }
컨트롤러 생성
$ nest g co # nest generate controller


import { Controller, Get } from '@nestjs/common'; @Controller('movie') // baseURL/movie <- 가 진입점이 됨. export class MovieController { @Get() // baseURL/movie 에 진입 했을 때를 담당함. getAll() { return 'This will return all movies'; } }

CRUD - Create
import { Controller, Delete, Get, Param, Post, Put } from '@nestjs/common'; @Controller('movie') // baseURL/movie <- 가 진입점이 됨. export class MovieController { @Post() create() { return 'This will create a movie'; } }

CRUD - Read, Read with parameter
import { Controller, Get, Param } from '@nestjs/common'; @Controller('movie') // baseURL/movie <- 가 진입점이 됨. export class MovieController { @Get() // baseURL/movie 에 진입 했을 때를 담당함. 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
과 @Param
에 명시한 이름은 서로 동일해야하지만, 사용할 이름을 명시할 때는 다르게 지어도 됨.

CRUD - Update
Put
: 리소스의 전체 내용을 변경함
Patch
: 리소스의 일부만 변경함
express.js에서 body를
json
으로 리턴하려면 설정을 좀 더 만져야 했으나, nest에서는 그냥 됨import { Controller, Delete, Get, Param, Post, Put } from '@nestjs/common'; @Controller('movie') // baseURL/movie <- 가 진입점이 됨. export class MovieController { @Put('/:id') put(@Param('id') movieId: string, @Body() newMovieData) { return { updatedMovieId: movieId, ...newMovieData, }; } @Patch('/:id') patch(@Param('id') movieId: string, @Body() updateData) { return { updatedMovieId: movieId, ...updateData, }; } }


CRUD - Delete
import { Controller, Delete, Get, Param, Post, Put } from '@nestjs/common'; @Controller('movie') // baseURL/movie <- 가 진입점이 됨. export class MovieController { @Delete('/:id') remove(@Param('id') movieId: string) { return `This will delete a movie with the id : ${movieId}`; } }
