목차

- nest cli을 이용한 code 생성

- Routing

- Request Object

- Response

- Header

- Redirect

- Payload


 

Nest의 Controller는  우리가 잘 알고 있는 MVC 패턴에서 말하는 그 Controller를 뜻한다.

요청을 받고 처리된 응답을 돌려주는 역할을 한다.

간단히 컨트롤러 작성법과 주로 사용하는 데코레이터( spring의 어노테이션)을 정리해보았다.

 

nest cli을 이용한 code 생성

Nest의 경우 cli를 이용하면 간편하게 샘플 코드를 생성해준다.

//controller 생성
nest g controller [yunji]

//간단한 CRUD 생성
nest g resource [yunji]

 

Routing

컨트롤러의 기능 중 라우팅 기능을 구현하는 방법에 대해 알아보자.

스프링을 사용해봤다면, 거의 동작 방식은 동일하다.

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


@Controller() //경로 설정하지 않을 경우 루트 경로로 인식된다.
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get() //마찬가지로 경로 설정하지 않을 경우 default get 요청으로 인식된다.
  getHello(): string {
    return this.appService.getHello();
  }
  
  @Get('/hello') // 이렇게 지정할 경우 GET localhost:8080/hello 로 요청할 경우 실행된다.
   getHello2(): string {
     return this.appService.getHello();
   }
}

라우팅 패스는 와일드 카드를 이용해서도 작성 할 수 있다.

별표(*)를 사용하면 어떤 문자가 와도 상관없이 해당 라우팅된 로직으로 이동한다.

 

실제로 아래처럼 작성한 후 요청해보았다.

    @Get('/he*o')
    test(){
        console.log('test');
    }

아래 요청 모두 하나의 라우팅으로 처리되어 test 로그를 남긴다.

GET http://localhost:3000/heo

GET http://localhost:3000/he123o

GET http://localhost:3000/he123123123o

 

Request Object

고객이 어떤 요청을 할 때 서버가 원하는 정보를 함께 전송할 때가 있다.

Nest는 요청과 함께 전달되는 데이터를 핸들러가 다룰 수 있는 객체로 변환한다.

이렇게 변환된 객체는 @Req() 데코레이터를 이용해서 다룰 수 있다.

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

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

  @Get()
  getHello(@Req() req: Request): string { // request  객체로 변환
    console.log(req);
    return this.appService.getHello();
  }
}

실제로 req를 log에 찍으면 생각보다 방대한 정보가 찍힌다.

실습을 통해 확인하거나 https://expressjs.com/en/api.html#req 여기를 참조하자.

 

실제로는 request 객체 전체를 다루기 보다는 @Query, @Param 등 데코레이터를 이용하니 참고만 하도록!

 

Response

nest는 기본적으로 POST 응답코드 201을 제외한 GET, PATCH, DELETE, PUT은 200코드를 응답하도록 설정되어있다.

요청 응답시 응답코드와 응답 바디를 설정하거나, 변경하려면 아래처럼 @Res 데코레이터를 이용할 수 있다.

@Get('/test')
findAll(@Res() res) {
   return res.status(201).send('success');
}

아래처럼 응답 코드만 변경하기 위해서 @HttpCode 를 사용하고, 파라미터나 바디는 @Param, @Body를 이용할 수도 있다.

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

@HttpCode(202)
@Patch(':id')
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
  return this.usersService.update(+id, updateUserDto);
}

 

Header

nest 는 응답 코드의 header도 자동으로 생성해준다.

따로 custom한 header 정보를 입력하고 싶다면 @Header 데코레이션을 이용하도록 하자.

 

@Get('/test')
@Header('Custom', 'Test Header')
findAll(@Res() res) {
    return res.status(201).send('success');
}

 

Redirect

특정 요청에서는 요청 고객을 다른 페이지로 이동시키고 싶은 경우가 있다.

이때 사용할 수 있는 것이 @Redirect 데코레이터다.

@Redirect('https://naver.com', 301)
@Get('/naver')
findOne() {
    console.log('naver test');
}

 

Rout Parameter

여기서 말하는 라우트 파라미터는 path 파라미터 라고도 한다.

@Param 데코레이터로 주입받을 수 있다.

여러가지 파라미터가 전달될 경우 라우트 파라미터를 받는 방법은 두 가지다.

 

1. 객체로 한 번에 받는 방법

@Delete(':userId/memo/:memoId')
deleteUserMemo(@Param() params: { [key: string]: string }) {
	return `userId: ${params.userId}, memoId: ${params.memoId}`;
}

2. 라우팅 파라미터를 각자 받는 방법

@Delete(':userId/memo/:memoId')
deleteUserMemo(
  @Param('userId') userId: string,
  @Param('memoId') memoId: string,
) {
  return `userId: ${userId}, memoId: ${memoId}`;
}

일반적으로는 각자 파라미터를 받는 방식을 많이 사용한다.

 

Payload

페이로드란, 쉽게 말해 spring에서의 body를 의미한다.

nest는 본문을 DTO로 정의해서 쉽게 다룰 수 있도록 @Body 데코레이터를 지원한다.

export class CreateUserDto {
  name: string;
  email: string;
}

@Post()
create(@Body() createUserDto: CreateUserDto) { //이렇게 바디로 받기 가능
  const { name, email } = createUserDto;

  return `유저를 생성했습니다. 이름: ${name}, 이메일: ${email}`;
}

 

 

다음번엔 프로바이더에 대해서 알아보도록 하자.

 

 

출처 : NestJS로 배우는 백엔드 프로그래밍

+ Recent posts