개발일지
Nest.js 모듈
index.ys
2023. 8. 14. 19:13
모듈
- 여러 작은 단위의 컴포넌트들을 조합하여 큰 작업을 수행할 수 있게 하는 단위
- Nest 앱이 실행되기 위해서 하나의 루트 모듈이 존재하고 이 루트 모듈(AppModule)은 다른 모듈들로 구성됨
- 여러 모듈에 각기 맡은 바 책임을 나누고 응집도를 높이기 위함
- 유사한 기능끼리 모듈로 묶어야함
- import: 이 모듈에서 사용하기 위한 프로바이더를 가지고 있는 다른 모듈을 가져옴
- controllers / providers : 모듈 전반에서 컨트롤러와 프로바이더를 사용할 수 있도록 Nest가 객체를 생성하고 주입
- export: 이 모듈에서 제공하는 컴포넌트를 다른 모듈에서 가져오기해서 사용하고자 한다면 export를 해야함
AppModule
- 애플리케이션의 Root 모듈
- CoreModule만을 가져오고 CoreModule에서 가져온 CommonModule을 다시 내보내면 AppModule에서 CommonModule을 가져오지 않아도 CommonModule을 사용가능
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CoreModule } from './core/core.module';
@Module({
//CoreModule만을 가져오고 CoreModule에서 가져온 CommonModule을
//다시 내보내면 AppModule에서 CommonModule을 가져오지 않아도 사용가능
imports: [CoreModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
CoreModule
- CoreModuled은 CommonModule을 가져온 후 다시 내보냄
import { Module } from '@nestjs/common';
import { CommonModule } from 'src/common/common.module';
@Module({
//CoreModule은 CommonModule을 가져운 후 다시 내보냄
imports: [CommonModule],
exports: [CommonModule],
})
export class CoreModule {}
CommomModule
- CommonModule에는 CommonService를 제공함
import { Module } from '@nestjs/common';
import { CommonService } from './common-service';
@Module({
//CommonService를 제공하고있음
providers: [CommonService],
exports: [CommonService],
})
export class CommonModule {}
CommonService
- Hello from CommonService라는 문자열 리턴
import { Injectable } from '@nestjs/common';
@Injectable()
export class CommonService {
hello(): string {
//CommonService에서 제공하는 기능
return 'Hello from CommonService';
}
}
AppCotroller
- /common-hello 경로로 get요청시
- Hello from CommonService라는 문자열 리턴
import { Controller, Get, Inject } from '@nestjs/common';
import { CommonService } from './common/common-service';
@Controller()
export class AppController {
constructor(
//Appcontroller에 CommonService계층 의존성 주입
private readonly commonService: CommonService,
) { }
@Get('/common-hello')
getCommonHello(): string {
return this.commonService.hello();
}
}
전체로직
- http://localhost:3000/common-hello경로로 GET요청
- app.controller에서 요청을 받아 CommonService의 getHello 메소드 실행