컨트롤러

서재·2023년 6월 15일

NestJS

목록 보기
3/4
post-thumbnail

컨트롤러

MVC 패턴에서의 컨트롤러

클라이언트로부터 요청(request)을 받고 처리된 결과를 응답(response)으로 돌려준다


🛠️ 컨트롤러 생성

$ cd [프로젝트 경로]
$ nest g controller [이름]
$ nest g co [이름]

🛸 CRUD 보일러플레이트 코드 생성

$ nest g resource [이름]

🧭 라우팅

해당하는 경로로 들어오는 요청 처리
정규표현식 사용 가능

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

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

  @Get('/hello')
  getHello(): string{
    return this.appService.getHello();
  }
}

localhost:3000/app/hello


🤲 요청 - Request

HTTP 요청
쿼리 스트링 , 매개변수 , 헤더 , 본문 ...

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 {
    console.log(req);
    return this.appService.getHello();
  }
}

API 사용 시 req를 직접 다루는 경우는 드물다

🐈️ Nest : @Query(), @Param(key?: string), @Body() 제공


🖐️ 응답 - Response

Controller의 각 메소드가 리턴하는 값 string

🐈️ Nest : 객체를 return할 경우 직렬화를 통해 JSON로 자동 변환

✔️ 성공 응답 코드

경로HTTP 메소드응답 상태 코드
/usersPOST201
/usersGET200
/users/1GET200
/users/1PATCH200
/users/1DELETE200

Express : @Res로 응답 객체를 직접 다루는 법


@Get()
findAll(@Res() res) {
  const users = this.usersService.findAll();
  
  return res.status(200).send(users);
}

🐈️ Nest : @HttpCode() 제공

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

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

❌ 400 Bad Request

요청 도중 에러 발생 / 예외 처리

throw new BadRequestException('예외 메시지');

헤더 - Header

클라이언트와 서버가 요청 또는 응답으로 부가적인 정보를 전송할 수 있도록 함

🐈️ Nest : 응답 헤더 자동 구성

커스텀 헤더

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

@Header('Custom', 'Test Header')
@Get(':id')
findOneWithHeader(@Param('id') id: string) {
  return this.usersService.findOne(+id);
}

리디렉션 - Redirection

서버가 요청을 처리 후,
요청한 클라이언트를 다른 페이지로 이동

🐈️ Nest : @Redirect 제공

import { Redirect } from '@nestjs.common';

@Redirect('https://nestjs.com', 301)
@Get(':id')
findOne(@Param('id') id: string) {
  return this.usersService.findOne(+id);
}

라우트 매개변수

패스 매개변수

동적 라우팅 : id

@Param으로 주입받음

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

하위 도메인 라우팅

패스 매개변수

동적 라우팅 : id

@Param으로 주입받음

@Controller({ host: 'api.example.com' })
export class ApiController {
  @Get()
  index(): string {
    return 'Hello, API';
  }
}
$ curl http://localhost:3000
Hello World!

$ curl http://api.localhost:3000
Hello, API

페이로드 Payload

본문 body

POST, PUT, PATCH 요청 처리에 필요한 데이터

NestJS에서는 DTO가 구현되어 있어 본문을 쉽게 다룬다

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

@POST()
create( @Body() createUserDto: CreateUserDto ){
  const { name, email } = createUserDto;
  
  return `유저 생성 완료. 이름: ${name}, 이메일: ${email}`
}

한용재 저, 『NestJS로 배우는 백엔드 프로그래밍』, 제이펍, 2022.

profile
입니다.

0개의 댓글