728x90

스프링에서도 최근에는 모듈간의 의존성을 만들어서 멀티모듈로 개발을 했었다.

그렇게 개발하는 방법이 중복되는 코드를 줄일 수 있기 때문이다.

 

Nest에서도 해당 방법으로 개발을 해보도록 하자.

 

우선 생성할 프로젝트의 구조는 다음과 같다.

Cpu module과 Disk module에서 Power module을 가져와서 사용하고, 최종적으로는 그 모듈들을 Computer Module에서 사용하는 것이다.

단순히 기능만 사용하는 것이기 때문에 Controller는 Computer module에만 생성하면 될 것이다.

 

모듈들은 미리 생성을 해두었고 우선 가장 기본이 되는 Power module부터 만들어보자.

nest g service power

 

그리고 해당 서비스에 간단한 메서드를 추가해보았다.

@Injectable()
export class PowerService {

    supplyPower(amount: number){
        console.log(`${this.constructor.name} 클래스에서 ${amount}의 전력을 공급했습니다.`)
    }
}

가장 기본적으로 전력을 공급하는 역할을 할 것이고, 해당 클래스의 정보를 확인하기 위해 값을 추가해보았다.

 

그리고 PowerModule에서 해당 서비스를 exports 해준다.

@Module({
  providers: [PowerService],
  exports: [PowerService]
})
export class PowerModule {}

이렇게 하면 PowerModule을 import한 다른 모듈에서 PowerService를 사용할 수 있게 된다.

 

마찬가지로 Cpu module과 Disk module에서 해당 모듈들을 가져가 사용해보자.

먼저 Disk module이다.

 

Disk module에서는 Power module을 가져오고, DiskService를 export 해야하니 다음과 같이 작성한다.

@Module({
  providers: [DiskService],
  imports: [PowerModule],
  exports: [DiskService]
})
export class DiskModule {}

 

그리고 service에서는 그냥 같은 모듈이라고 생각하며 의존성을 가져온다.

@Injectable()
export class DiskService {

    constructor(
        private readonly powerService: PowerService
    ) {}

    getData(): number[]{
        this.powerService.supplyPower(10);
        
        return [Math.floor(Math.random() * 10),  Math.floor(Math.random() * 10)];
    }
}

 

CpuService에서는 그냥 다음과 같이 만들어줬다.

@Injectable()
export class CpuService {
    constructor(private readonly powerService: PowerService) { }
    
    calculate(a: number, b: number): number {
        this.powerService.supplyPower(20);
        return a + b;
    }
}

 

이제 이 모든 것을 사용할 Computer module이다.

 

사용할 모듈들은 imports에 추가하고, 컨트롤러를 빼준다.

@Module({
  providers: [ComputerService],
  controllers: [ComputerController],
  imports: [CpuModule, DiskModule]
})
export class ComputerModule {}

 

@Injectable()
export class ComputerService {

    constructor(private readonly cpuService: CpuService,
                private readonly diskService: DiskService) {}

    useCom(): number{
        const numbers = this.diskService.getData()
        return this.cpuService.calculate(numbers[0], numbers[1]);
    }

}

코드를 다음과 같이 작성하고 요청을 해보니

 

이렇게 Power module의 서비스를 이용하는 것을 볼 수 있다.

 

같은 인스턴스인지 궁금해서 랜덤값으로 값을 부여하고 출력해보았는데, 같은 값이 나왔다.

같은 서버 내에서는 imports 하더라도 싱글톤으로 같은 인스턴스를 공유하고 있는 것을 알 수 있었다.

 

 

 

이렇게 다른 모듈에서 export, import 하게 되면 컨테이너에서 해당 import 클래스들을 가져올 수 있게 된다.

+ Recent posts