본문 바로가기

Backend/파본것들

[nestjs] Module이란, 순환 참조 오류

Error

Nest can't resolve dependencies of the userscontroller (usersservice, ?). please make sure that the argument authservice at index [1] is available in the usersmodule context.

나의 경우 계속 이런 오류가 생겼다... 의존성 관계를 잘 파악하지 못해서 생긴 오류라는 생각이 들었고 Module을 어떻게 작성해야하는지를 찾아봤다.

Module이란

각각의 기능을 담당하는 Controller와 Providers는 Module Decorator에 등록되고 이 각 기능 Module들을 App Module에 import하여 최종적으로 NestFactory로 create되는 flow를 가지고 있다.

나의 경우, User Module과 Auth Module이 있었고 UserController에서 UserService가 아닌 AuthService의 의존성을 주입하려고 할 때, 해당 의존성은 User Module이 아닌 Auth Module에서 참조한다. 의론에 의하면 Module의 의존성이 서로 공유가 되기 때문에 별도의 설정 없이 사용할 수 있을 것 같다. 하지만 위와 같은 오류가 발생했다.

이유눈 UserController에서 주입한 AuthService의 의존성을 찾을 수 없다는 것이고 의존성을 사용하기 위해서는 UserModule에서 AuthService를 포함하고 있는 Module을 import해야 한다! 

그리고 이때, UserModule에서 AuthModule을 import한다고 바로 쓰진 못하고 AuthModule에서 다른 Module에서 사용하고자 할 의존성을 export해줘야 한다.

 

하지만!!!

Error2

Nest cannot create the module instance

인증의 구조 상, UserModule과 AuthModule이 서로를 import할 수 밖에 없는 상황이기에 순환참조오류가 발생한다.

 

@Controller('users')
export class UsersController {
  constructor(
    private readonly usersService: UsersService,
    private authService: AuthService,
  ) {}
}

 

@Injectable()
export class AuthService {
    constructor(
        private usersService: UsersService,
        private jwtService: JwtService,    
    ) {}
}

Circular Dependency

UserModule에 있는 UserService와 AuthModule에 있는 AuthService가 서로 의존주입을 하려하면 문제가 발생하여 실행되지 않는다.

이때, 문제를 해결하기 위해 forwardRef를 사용해야 한다.

 

@Module({
  imports: [
    forwardRef(() => UsersModule),
    PassportModule,
    JwtModule.register({
      secret: jwtConstants.secret,
      signOptions: { expiresIn: '60s' },
    }),
  ],
  providers: [AuthService, LocalStrategy, JwtStrategy],
  exports: [AuthService],
})
export class AuthModule {}

 

@Module({
  imports: [
    forwardRef(() => AuthModule),
    TypeOrmExModule.forCustomRepository(
      [UsersRepository]
    )
  ],
  controllers: [UsersController],
  providers: [UsersService],
  exports: [UsersService],
})
export class UsersModule {}

 

참고한 블로그

https://medium.com/crocusenergy/nestjs-modules-%EA%B0%9C%EB%85%90-%EB%B0%8F-%EC%8B%A4%EC%8A%B5-758b1328e9e7

 

[NestJS] Modules 개념 및 실습

저번 시간에는 [NestJS] Providers 개념 및 실습 을 알아보았습니다. 이번 시간에는 NestJS의 Modules 개념을 살펴보고 실습을 진행하겠습니다.

medium.com

https://velog.io/@peter0618/NestJs-circular-dependency-%EB%AC%B8%EC%A0%9C-%ED%95%B4%EA%B2%B0

 

NestJS circular dependency 문제 해결

예를 들어, Module-A에 있는 Service-A와 Module-B에 있는 Service-B가 서로 의존주입을 하려 하면 문제가 발생하여 실행되지 않습니다.이를 해결하기 위한 간단한 방법은 "forwardRef" 입니다.위와 같이 두 모

velog.io

https://docs.nestjs.com/fundamentals/circular-dependency

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac

docs.nestjs.com

 

'Backend > 파본것들' 카테고리의 다른 글

[nestjs] Authentication, bcrypt  (0) 2023.02.14
static 이란, 쓰는 이유  (0) 2023.01.30
const와 readonly의 차이  (0) 2023.01.28