개발에 AtoZ까지

[NestJS Document 파헤치기] Controller 본문

백엔드/Node.js

[NestJS Document 파헤치기] Controller

AtoZ 개발자 2022. 10. 23. 13:25
반응형

목차

  1. Controller 정의 및 사용
  2. NestJS Controller 관련 Decorator 종류
  3. 마무리

 

Controller 정의 및 사용


Controller란?

Controller란 Client에서 들어오는 요청을 처리하고 Client에게 처리결과를 전달해주는 역할 한다.
다시말하면 A라는 요청이 들어오면(Request) 이 요청을 처리할 수 있는게 누구인가(Service) 하고 찾아서 처리할 수 있는 곳에 전달하고 처리 후 결과를 다시 Client에게 전달하는것이다.

Controller 사용

import { Controller, Get } from '@nestjs/common';

@Controller('cats')  //@Controller => Decorator
export class CatsController {
  @Get()        // Http Method get을 Decorator로 표현
  findAll(): string {
    return 'This action returns all cats';
  }
}

위의 코드를 풀이하면 Client가 localhost:3000/cats로 요청을 하면 This action returns all cats 라고 응답하는것입니다.
@Controller 라는 Decorator를 통해서 localhost:3000/cats 라는 요청과 CatsController라는 Class를 연결하여 Nest가 Routing Map을 생성할 수 있도록 합니다.

 

NestJS Controller 관련 Decorator 종류


@HttpCode

Http response의 status 코드를 handling하는 Decorator로 기본적으로 201 코드를 사용하는 Post 이외의 Http Method에서는 200 으로 자동 설정되어 있다.

 

@Redirction

응답을 특정 Url로 Redirection 하고 싶을때 @Redirection Decorator를 사용한다. 또는 res.redirect을 사용하는 방법도 있다.
Redirection의 매개변수의 Type은 아래와 같다.

{
  "url": string,
  "statusCode": number
}
@Get()
@Redirect('https://nestjs.com', 301)
getUser(): IUser {
  .......
  return user;
}

@Get()
@Redirect('https://nestjs.com', 301)
getUser(@Res() res: Response): IUser {
  .......
  res.redirect('https://nestjs.com', 301)
  return user;
}

@Param

parameter의 값을 자동으로 캐치해준다.

@Get(':id')
findOne(@Param() params): string {
  console.log(params.id);
  return `This action returns a #${params.id} cat`;
}

 

path Varialbe 과 query-string의 차이

더보기

- parameter는 특정 패턴에 대해서 값을 가져오는 형태

- query-string는 key-value 형태에서 key를 가지고 value 값을 가져오는 형태


ex) loacalhost/user/1 => user/:id 이런식으로 controller에 정의 해주면  id가 1이 되는것이다.
ex) localhost/about?user=1&phone=11111 => user=1이고 phone=11111 이런식으로 구성되어 있는것이 query-string 방식이다.


효과는 같지만 쓰임새가 다르다.

Path Variable은 특정 인덱스에 대한 조회, Query String 은 특정 값으로 필터링할때 조금 더 적합할 수 있다.

Domain Routing

@Controller데코레이터는 들어오는 요청의 HTTP 호스트가 특정 값과 일치하도록 요구하는 옵션을 사용할 수 있습니다

@Controller({ host: 'admin.example.com' })
export class AdminController {
  @Get()
  index(): string {
    return 'Admin page';
  }
}

@body

body로 담겨져서 오는 데이터값을 dto에 담아주는 역할
만약 아래와 같은 예시에서 클라이언트에서 body에 type이라는 값을 서버에게 전달하였더라도 createCatDto에는 해당 데이터유형을 정의하지 않았기 때문에 값을 전달받지 못한다.

export class CreateCatDto {
  name: string;
  age: number;
  breed: string;
}

@Post()
async create(@Body() createCatDto: CreateCatDto) {
  return 'This action adds a new cat';
}

어떻게 이렇게 동작하는지 살펴보겠다.
사실 nest.js에는 pipe라는게 존재한다. pipe는 추후 포스트에서 언급하겠지만 간략히는 데이터의 유효성을 체크하는 기능을 한다고 보면 좋을것 같다.
사용자가 커스텀하지않아도 기본적으로 global pipe가 실행된다. 기본 default 값을 보면 whitelist 옵션이 true인데 이것이 사용자가 정의한 변수값에 대해서만 데이터를 가져오겠다라는 뜻이다.

app.useGlobalPipes(
  new ValidationPipe({
    whitelist: true,
  }),
);

 

마무리

nest.js의 controller를 공부하다보니 데코레이터를 사용해서인지 java spring과 비슷하다는 느낌을 많이 받았다.
추가적으로 싱글톤을 사용한다는것도 비슷했다. 아직 Deepdive한지 별로 안됐지만 더 Deepdive해서 나중에 spring과 비교해보는 시간을 가지는것도 좋을것같다.

반응형

'백엔드 > Node.js' 카테고리의 다른 글

[NestJS] 정의와 Express 비교  (0) 2022.09.18
Comments