ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • nestjs에서 멀티 DB 설정 및 셋팅
    NodeJS 2022. 10. 28. 15:03

    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일을 날리게 되네요. :(

    참고자료

Designed by Tistory.