NestJS controller
본 포스팅은 사이드프로젝트 스케치데브를 사용하면서 공부한 nestjs를 정리한 글입니다.
스케치데브가 궁금하시다면: https://sketchdev.kr
스케치데브 - 개발자 캐치마인드
스케치데브는 개발자들만의 IT용어로 즐기는 스케치퀴즈 연상 캐치마인드 게임입니다. 고득점을 한번 노려보세요!
sketchdev.kr
라우팅하기
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
Controller, Get이라는 Decorator를 줘야한다.
(Spring 개발자 출신 아니랄까봐 완전 빼다박았다. findAll() 이라는 함수명까지. )
Request 정보 가져오기(query param, request body 등)
default는 express를 쓴다.
import { Controller, Get, Req } from '@nestjs/common';
import { Request } from 'express';
@Controller('cats')
export class CatsController {
@Get()
findAll(@Req() request: Request): string {
return 'This action returns all cats';
}
}
아래처럼 wildcard route도 가능하다. wow
@Get('ab*cd')
findAll() {
return 'This route uses a wildcard';
}
response code나 header를 decorator로 유연하게 설정하는 것이 가능하다.
@Post()
@HttpCode(204)
create() {
return 'This action adds a new cat';
}
@Post()
@Header('Cache-Control', 'none')
create() {
return 'This action adds a new cat';
}
Redirecton도 decorator로.
@Get()
@Redirect('https://nestjs.com', 301)
쿼리
@Get('docs')
@Redirect('https://docs.nestjs.com', 302)
getDocs(@Query('version') version) {
if (version && version === '5') {
return { url: 'https://docs.nestjs.com/v5/' };
}
}
라우트 파라미터
@Get(':id')
findOne(@Param() params): string {
console.log(params.id);
return `This action returns a #${params.id} cat`;
}
@Get(':id')
findOne(@Param('id') id: string): string {
return `This action returns a #${id} cat`;
}
비동기
그냥 promise로 return하면 프레임워크에서 알아서 비동기로 처리한다. 매력적이다.
@Get()
async findAll(): Promise<any[]> {
return [];
}
RxJS 스타일도 가능
@Get()
findAll(): Observable<any[]> {
return of([]);
}
요청 페이로드
export class CreateCatDto {
name: string;
age: number;
breed: string;
}
Dto라는 클래스를 만들어 사용한다.
@Post()
async create(@Body() createCatDto: CreateCatDto) {
return 'This action adds a new cat';
}
풀 리소스 샘플
import { Controller, Get, Query, Post, Body, Put, Param, Delete } from '@nestjs/common';
import { CreateCatDto, UpdateCatDto, ListAllEntities } from './dto';
@Controller('cats')
export class CatsController {
@Post()
create(@Body() createCatDto: CreateCatDto) {
return 'This action adds a new cat';
}
@Get()
findAll(@Query() query: ListAllEntities) {
return `This action returns all cats (limit: ${query.limit} items)`;
}
@Get(':id')
findOne(@Param('id') id: string) {
return `This action returns a #${id} cat`;
}
@Put(':id')
update(@Param('id') id: string, @Body() updateCatDto: UpdateCatDto) {
return `This action updates a #${id} cat`;
}
@Delete(':id')
remove(@Param('id') id: string) {
return `This action removes a #${id} cat`;
}
}
Response를 함수 내부에서 조작하고 싶다.
Res decorator 로 받아서 조작하면 된다.
@Controller('cats')
export class CatsController {
@Post()
create(@Res() res: Response) {
res.status(HttpStatus.CREATED).send();
}
@Get()
findAll(@Res() res: Response) {
res.status(HttpStatus.OK).json([]);
}
}
참고
https://docs.nestjs.com/controllers
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac
docs.nestjs.com
글 읽어주셔서 감사합니다.