[nestJs]barrel로 인한 dependency injection 이슈

코드깎는 노인·2022년 3월 22일
1

에러

nest.js bootstrap과정에서는 발생하지 않았지만 typeorm migration파일 생성시 에러 발생

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

Barrel이란?

하나의 파일에서 re-export하여 import구문을 축약하여 코드를 더 깨끗하게 유지보수할 수 있는 방식

barrel을 사용하지 않을 시

// ./src/app.ts
import { a } from "./util/a";
import { b } from "./util/b";
import { c } from "./util/c";
console.log(a, b, c);

barrel을 사용시

// ./src/app.ts
import { a, b, c } from "./util/barrel";
console.log(a, b, c);

barrel 파일

// ./src/util/barrel.ts
export from "./util/a";
export
from "./util/b";
export * from "./util/c";

계층구조

.
└── src/
├── app.ts
└── util/
├── a.ts
├── b.ts
├── c.ts
└── barrel.ts

현상

InjectRepository데코레이터에 의해 의존성 주입시 인스턴스가 undefined되어 발생하였다.

원인

정확한 원인을 찾지 못했지만 ormconfig에 설정된 엔티티 파일경로에 따라 첫번째 로딩 후 클래스들이 캐싱되는데

barrel로 인하여 파일경로 참조값에 오류가 있는것으로 보인다.

해결

방법1

barrel없이 직접 import한다.

import {Entity} from './' \\via index.ts

to

import {Entity} from './Entity'

방법2

ormconfig의 엔티티 경로를 glob pattern에서 barrel파일로 변경한다

entities: [ 'src/entity/**/*.ts' ]

to

entities: [ 'src/entity/index.ts' ]

참조
https://stackoverflow.com/questions/63257409/nest-js-circular-reference-at-the-moment-to-inject-a-repository
https://github.com/typeorm/typeorm/issues/420
https://github.com/nestjs/nest/issues/1181

profile
내가 볼려고 만든 블로그

0개의 댓글