[오류 일지] @InjectRepository - Circular Reference Error

Song·2021년 12월 26일
0

오류일지

목록 보기
4/5

이슈

@InjectRepository 내에서 순환 참조 오류가 발생하였다.

Error: A circular dependency has been detected inside @InjectRepository(). Please, make sure that each side of a bidirectional relationships are decorated with "forwardRef()". Also, try to eliminate barrel files because they can lead to an unexpected behavior too.

원인

보통 Nest.js에서 발생하는 순환 참조 오류는 A Service 모듈과 B Service 모듈이 서로를 의존하면서 발생하는데
이 때는 forwardRef() 를 이용해서 해결하는 방법이 있다.
(자세한 설명: https://docs.nestjs.com/fundamentals/circular-dependency)

그런데 @InjectRepository 는 다른 경우다.
아래 코드와 같이 Entity를 주입하는 과정에서 EntityClassundefined 라서 오류가 난 것.

@InjectRepository(EntityClass) private readonly repo: Repository<EntityClass>,

그 이유는 nest가 서버를 실행한 후 EntityClass를 선언하기도 전에 EntityClass를 참조하는 다른 모듈이 먼저 선언하며 발생한 것이다.

나같은 경우는 database.modules.ts 에서 설정한 entity 경로가 문제였는데
지정한 경로에 있는 entity class들이 선언되기도 전에 database 모듈에서 테이블을 읽으려고하니
당연히 undefined로 읽히며 오류가 발생하것이였다.

해결

database 모듈에서 지정한 경로에 있는 entity들은 어차피 사용하지 않는 클래스였기 때문에
해당 경로를 없애주며 오류를 해결했다.

느낀점

이번에 오류가 발생한 database 모듈은 다른 곳에서 복붙해온 건데
다른곳에서 잘 되었으니 이번에도 상관없겠지라는 안일한 생각으로 인해 미연에 방지할 수 있는 오류를 발견하지 못했던 거 같다.

결론: 한번 쓴 코드도 다시 보자

profile
Learn From Yesterday, Live Today, Hope for Tomorrow

1개의 댓글

comment-user-thumbnail
2022년 11월 8일

덕분에 순환종속 해결 실마리 찾아갑니다

답글 달기