Controller prefix와 HTTP method decorator로 요청 경로를 정의합니다.
@Controller는 관련 endpoint를 묶고 @Get, @Post 등은 method와 하위 경로를 연결합니다. Controller는 HTTP 입력과 응답 변환에 집중합니다.
업무 계산과 저장소 접근은 Service로 이동해 transport 책임과 분리합니다.
리소스 이름은 명사 복수형을 사용하고 action 동사보다 HTTP method 의미를 활용합니다.
Controller에 DB 쿼리와 긴 업무 규칙을 직접 넣으면 테스트와 재사용이 어려워집니다.
로컬 프로젝트에서 확인해보세요GET /courses/:id endpoint를 추가하세요.
import "reflect-metadata";
import { Controller, Get, Module } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
@Controller("courses")
class CourseController {
@Get() findAll() {
return [
{ id: 1, title: "NestJS" },
{ id: 2, title: "DI" },
];
}
}
@Controller()
class HomeController {
@Get() home() {
return `<main><h1>Controller</h1><a href="/courses">강좌 API 열기</a></main>`;
}
}
@Module({ controllers: [HomeController, CourseController] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(4173, "0.0.0.0");
}
bootstrap();