MVC 패턴에서의 컨트롤러
클라이언트로부터 요청(request)을 받고 처리된 결과를 응답(response)으로 돌려준다
$ cd [프로젝트 경로]
$ nest g controller [이름]
$ nest g co [이름]
$ 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
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() 제공
Controller의 각 메소드가 리턴하는 값 string
🐈️ Nest : 객체를 return할 경우 직렬화를 통해 JSON로 자동 변환
| 경로 | HTTP 메소드 | 응답 상태 코드 |
|---|---|---|
| /users | POST | 201 |
| /users | GET | 200 |
| /users/1 | GET | 200 |
| /users/1 | PATCH | 200 |
| /users/1 | DELETE | 200 |
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);
}
요청 도중 에러 발생 / 예외 처리
throw new BadRequestException('예외 메시지');
클라이언트와 서버가 요청 또는 응답으로 부가적인 정보를 전송할 수 있도록 함
🐈️ Nest : 응답 헤더 자동 구성
커스텀 헤더
import { Header } from '@nestjs/common';
@Header('Custom', 'Test Header')
@Get(':id')
findOneWithHeader(@Param('id') id: string) {
return this.usersService.findOne(+id);
}
서버가 요청을 처리 후,
요청한 클라이언트를 다른 페이지로 이동
🐈️ 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
본문 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.