controller는 사용자의 request를 받아 정보를 처리하고 response를 반환하는 역할을 한다.
한마디로 https://github.com에 들어가는 것이 request고 페이지 데이터를 받아오는 것이 response.
이 경우 https://github.com/iofjasd/cnisadjf/ejiofn/ncjklasnv 이런식으로 경로가 길어질 수 있다.
이에 따라 controller도 여러 개 만들어질 수 있다.
아직까지는 단순히 CRUD만 하고, parms나 body 또는 header로 받아오는 것 뿐이라 쉬운 편이다.
nest는 nest g co [name]으로 간단하게 controller을 만들 수 있다. 명령어를 사용하면 알아서 필요한 부분에도 작성해준다.
명령어를 사용하지 않는다면...
name.controller.ts 와 name.controller.spec.ts 파일을 만든다.app.module.ts의 controller에 name 을 추가하고 import를 한다.이렇게 귀찮은 작업을 해줘야한다.
귀찮지 않으려면 꼭 명령어로 만들어주자.
// cats.controller.ts
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get('all')
findAll(): string {
return 'This action returns all cats';
}
}
이 경우 localhost:3000/cats/all 경로로부터 get을 하면 This action retuens all cats 문자열을 반환해준다.
@Controller('cats') @Get('all')은 @Controller('cats/all') @Get()과 같은 결과를 낸다.
라우팅 하기 참 편하다!
Express를 쓴다면서 Request 어디감?일 것이다.@Get()
findAll(@Req() request: Request): string {
return 'This action returns all cats';
}
console.log로 찍어보면 request가 정상적으로 들어오는 것을 알 수 있다.
headers, body, params 등 여러 데이터를 끄집어 낼 수도 있다.
export class CreateCatDto {
name: string;
age: number;
breed: string;
}
@Post()
async create(@Body() createCatDto: CreateCatDto) {
return `This action add a new cat ${createCatDto.name}-${createCatDto.age}-${createCatDto.breed}`;
}
// CRUD 원칙에 따라 Post에는 별도의 param 없음
// param은 있어도 되고 없어도 되는 부분을 의미. 다만 있으면 알아보기 쉽다.
// 각 데코레이터에서 :는 param의 변수로 사용할 것인가?를 의미
// 이때 파라미터는 와일드카드(*)를 사용할 수 있다!
@Get(':<param>')
@Post()
@Put(':<param>')
@Delete(':<param>')
// http 상태 코드 반환
@HttpCode(<code>)
// 리다이렉트
@Redirect(<host>, <status_code>)
// 커스텀 반환 헤더
@Header(<key>, <value>)
@Request(), @Req(): Request req
@Response(), @Res()*: Response res
@Next() next
@Session() req.session
@Param(key?: string): JSON/<type> req.params / req.params[key], /cats/3 에서 3 부분을 담당
@Body(key?: string): DTO req.body / req.body[key] DTO의 내용에 맞는 요청만 받을 수 있음
@Query(key?: string): JSON/<type> req.query / req.query[key] /cats?name=앙골라 에서 ? 이후 부분을 담당
@Headers(name?: string): JSON/<type> req.headers / req.headers[name] JSON 이후 stringfy로 전체. 개별로 받아온 경우 각 타입으로.
@Ip(): String req.ip
@HostParam(): String req.hosts
여기서 @Res()의 경우에는 res.json이나 res.send를 호출하는데 문제가 있을 수 있다고 한다.
아래의 둘 중 하나를 사용해라고 적혀있다.
// 1.
res.status(<HttpStatus>).json([]);
// 2.
res.status(<HttpStatus>);
return []
몬가 오류가 뜬다면 매개변수에 @Res({ passthrough: true }) res: Response를 사용해보라고 한다.