파일 구조
src
├── app.controller.spec.ts // 테스트 코드
├── app.controller.ts // 컨트롤러
├── app.module.ts // 모듈
├── app.service.ts // 서비스
└── main.ts // 엔트리 포인트
파일별 역할 설명
- app.controller.spec.ts: 컨트롤러의 테스트 코드를 작성하는 파일입니다.
- app.controller.ts: API 요청을 처리하는 컨트롤러 파일입니다.
- app.module.ts: 모듈을 정의하는 파일로, 애플리케이션의 구조를 설정합니다.
- app.service.ts: 비즈니스 로직을 처리하는 서비스 파일입니다.
- main.ts: 애플리케이션의 엔트리 포인트로, Nest 애플리케이션을 시작합니다.
모듈, 컨트롤러, 서비스 간의 의존성 주입 및 실행 흐름
main.ts
main.ts 파일은 애플리케이션의 진입점으로, AppModule을 불러와 Nest 애플리케이션을 시작합니다.
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
app.module.ts
app.module.ts 파일에서는 모듈을 정의하고, 컨트롤러와 서비스를 결합합니다.
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController], // 컨트롤러 주입
providers: [AppService], // 서비스 주입
})
export class AppModule {}
app.controller.ts
app.controller.ts 파일에서는 엔드포인트를 정의하고, 서비스의 메서드를 호출합니다.
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {} // 서비스 의존성 주입
//private readonly를 쓰면 this.appService = appService 이런거 안써도됨
@Get('/hello') //여기에 엔드포인트 설정
getHello(): string { //반환타입을 string으로 지정
return this.appService.getHello(); // 서비스의 메서드 호출
}
}
app.service.ts
app.service.ts 파일에서는 비즈니스 로직을 정의합니다.
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
주요 개념 정리
- main.ts: 애플리케이션의 엔트리 포인트로, AppModule을 불러와 애플리케이션을 시작합니다.
- app.module.ts: 모듈을 정의하며, 컨트롤러와 서비스를 결합합니다. controllers와 providers 배열에 각각 컨트롤러와 서비스를 주입합니다.
- app.controller.ts: 엔드포인트를 정의하고, 요청을 처리하며, 필요한 서비스를 호출합니다.
- app.service.ts: 비즈니스 로직을 처리하며, 컨트롤러에서 호출될 메서드를 정의합니다.
오른쪽부터 api요청 -> module -> controller -> service
'nest.js' 카테고리의 다른 글
TypeScript Generics, Typescript-utility (2024.05.30) (1) | 2024.05.30 |
---|---|
Nest.js에서 GraphQL 사용해 보기 (2024.05.30) (0) | 2024.05.30 |
Nest.js ESLint, Prettier (2024.05.29) (0) | 2024.05.29 |
Nest.js 설치 및 기초 (2024.05.29) (0) | 2024.05.29 |
nest.js 접근제어자 (2024.05.29) (0) | 2024.05.29 |