1. Controller
- Routing(라우팅)
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
- 데코레이터 부분에 'cats'가 path 역할을 하여 /cats 이렇게 들어가게 된다.
- @Controller() 이렇게 아무것도 없을 경우 root path가 된다.
- Request Method
import { Controller, Get, Req } from '@nestjs/common';
import { Request } from 'express';
@Controller('cats')
export class CatsController {
@Get('action')
findAll(@Req() request: Request): string {
return 'This action returns all cats';
}
}
- 데코레이터로 @Get / @Post / @Put / @Delete 등을 사용할 수 있다.
- 위에 코드 예시처럼 Request Method 데코레이터 안에 명시해주면 Controller 데코레이터와 같이 path 역할을 하게 된다.
- Request object
@Request(), @Req() | req |
@Response(), @Res() | res |
@Next() | next |
@Session() | req.session |
@Param(key?: string) | req.params / req.params[key] |
@Body(key?: string) | req.body / req.body[key] |
@Query(key?: string) | req.headers / req.headers[name] |
@Headers(name?: string) | req.headers / req.headers[name] |
@Ip() | req.ip |
@HostParam() | req.hosts |
- 비동기
@Get()
async findAll(): Promise<any[]> {
return [];
}
- 비동기 함수는 Promise를 반환해야 한다.
- Dto 사용
export class CreateCatDto {
name: string;
age: number;
breed: string;
}
@Post()
async create(@Body() createCatDto: CreateCatDto) {
return 'This action adds a new cat';
}
- 전체 예시
cats.controller.tsJS
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`;
}
}
'JavaScript Dev. > Nest.js' 카테고리의 다른 글
Nest.js - middleware (0) | 2024.03.01 |
---|---|
Nest.js - Provider (0) | 2024.02.28 |
Nest.js - Module (0) | 2024.02.28 |
Nest.js 설치부터 기본 개념까지 (1) | 2024.02.06 |
Nest.js와 OOP(객체지향 프로그래밍) (0) | 2024.01.14 |