728x90
nestjs에서 멀티 DB 설정 및 셋팅
2개 이상(ex: Main, Read)의 DB를 사용하기 위해서는 AppModule에 TypeOrmModule을 2개 설정해야 합니다.
...
@Module({
imports: [
TypeOrmModule.forRootAsync({ // 이름이 없는 default 는 필수로 필요
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'sqlite',
database: configService.get('DB_HOST'),
dropSchema: configService.get('DB_DROP') === 'true',
entities: ['dist/**/*.entity{.ts,.js}'],
synchronize: configService.get('DB_SYNC') === 'true',
logging: configService.get('DB_LOGGING') === 'true',
logger: configService.get('LOGGING_WAY') ,
}),
}),
TypeOrmModule.forRootAsync({
name: 'Read', // 'Read' 용 DB생성
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
name: 'Read' // 테스트시 없을 경우 오류 발생
type: 'sqlite',
database: configService.get('DB_RO_HOST'),
dropSchema: configService.get('DB_DROP') === 'true',
entities: ['dist/**/*.entity{.ts,.js}'],
synchronize: configService.get('DB_SYNC') === 'true',
logging: configService.get('DB_LOGGING') === 'true',
logger: configService.get('LOGGING_WAY') ,
}),
}),
UserModule,
AuthModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(AppLoggerMiddleware).forRoutes('*');
}
}
사용하려는 모듈에서 아래와 같이 설정합니다.
...
@Module({
imports: [
TypeOrmModule.forFeature([Entity]),
TypeOrmModule.forFeature([Entity], 'Read'),
],
controllers: [SampleController],
providers: [SampleService], // 현재 모듈에서 사용
exports: [], // 다른 모듈에서 사용가능
})
export class SampleModule {}
service에서는 아래와 같이 사용합니다.
...
@Injectable()
export class SampleService {
constructor(
@InjectRepository(Entity)
private entityRepository: Repository<Entity>,
@InjectRepository(Entity, "Read")
private entityRoRepository: Repository<Entity>,
) {}
...
}
별게 아닌데, 막상 설정을 하다보면 2~3일을 날리게 되네요. :(
참고자료
'NodeJS' 카테고리의 다른 글
nestjs에서 jest TIP 정리 (0) | 2022.11.07 |
---|---|
공통 테이블을 상수로 전환 처리 (0) | 2022.10.31 |
typescript 객체 생성 유틸 (0) | 2022.10.28 |
javascript array에서 중복되는 객체 제거하기 (0) | 2021.12.14 |
nestjs에서 passport + SAML 로그인시 오류 발생 처리 (0) | 2021.12.12 |