dotenv.config를 활용해서 NODE_ENV에 따라 각각 다른 db를 연결했던것을
@nestjs/config 패키지를 활용해서 ConfigModule을 동적 모듈로 사용하는 방법으로 변경하기
✔️env파일 경로 설정하기
ConfigModule.forRoot()에 옵션값을 넘겨주면 동적 모듈을 생성할 수 있다.
(method) ConfigModule.forRoot(options?: ConfigModuleOptions): DynamicModule

옵션에는 이런 값들을 넣을 수 있는데
envFilePath에 env파일의 경로를 주면 해당 파일을 루트경로에 있는 .env대신 읽어서 환경변수를 구성한다.

환경변수 파일들은 src/configs/envs에 넣어놨고
참고사이트를 참고해서 NODE_ENV에 따라 다른 env파일의 경로를 리턴하고, 없으면 sample.env의 경로를 리턴하는 getEnvPath함수를 작성해서 envFilePath를 지정했다.
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: getEnvPath(`${__dirname}/configs/envs`),
isGlobal: true
})
],
그리고 isGlobal은 true로 설정해서 어디서든 ConfigService에 접근할 수 있게 한다.
Nest가 제공하는 ConfigModule은 .env 파일에서 읽어온 환경변수 값을 가져오는 프로바이더인 ConfigService가 있습니다. 이를 원하는 컴포넌트에서 주입하여 사용하면 됩니다.
ConfigService를 활용해서 환경변수를 가져와 db를 연결하려고 한다.
✔️ db연결
TypeOrmModule의 forRootAsync에는 TypeOrmModulesAsyncOptions형의 옵션을 줄 수 있다.
(method) TypeOrmModule.forRootAsync(options: TypeOrmModuleAsyncOptions): DynamicModule
TypeOrmModulesAsyncOptions은

이렇게 생겼는데 그중 useClass에 들어가는 TypeOrmOptionsFactory는

Promise<TypeOrmModuleOptions> | TypeOrmModuleOptions 를 리턴하는 createTypeOrmOptions를 가지고 있다.
그래서...
개발환경에 따라 다른 db를 연결하려면 환경변수값을 ConfigService로 가져오기 위해서 클래스로 만들어야 하는데
해당 클래스로 TypeOrmModule을 설정하려면 forRootAsync 메서드를 사용하고 useClass옵션에 해당 클래스를 주면 된다.
그리고 그 클래스는 TypeOrmOptionsFactory 타입이어야 하고, TypeOrmModuleOptions를 리턴하는 createTypeOrmOptions를 가지고있어야한다.
// typeorm.config.ts
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { TypeOrmModuleOptions, TypeOrmOptionsFactory } from "@nestjs/typeorm";
@Injectable()
export class TypeOrmConfigService implements TypeOrmOptionsFactory {
constructor(private configService: ConfigService) {}
createTypeOrmOptions(): TypeOrmModuleOptions {
return {
type: 'mysql',
host: this.configService.get('DATABASE_HOST'),
port: Number(this.configService.get('DATABASE_PORT')),
username: this.configService.get('DATABASE_USERNAME'),
password: this.configService.get('DATABASE_PASSWORD'),
database: this.configService.get('DATABASE_NAME'),
entities: [__dirname + '/../**/*.entity.{js,ts}'],
synchronize: Boolean(this.configService.get('DATABASE_SYNCHRONIZE'))
};
}
}
// app.module.ts
...
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: getEnvPath(`${__dirname}/configs/envs`),
isGlobal: true
}),
TypeOrmModule.forRootAsync({
useClass: TypeOrmConfigService
})
],
...
그래서 이렇게 작성해서 연결완료
(참고자료 보고 먼저 만들고 후학습!)
참고
https://dev.to/raphael_haecker/nestjs-and-typeorm-database-configuration-15ob
https://blog.devgenius.io/environment-variables-in-nest-js-b989bb0370bf
'TIL' 카테고리의 다른 글
| [프로그래머스/SQL] 가격이 제일 비싼 식품의 정보 출력하기: 정렬 vs 서브쿼리 (0) | 2024.07.26 |
|---|---|
| NestJS | TypeORM: entity 정의(soft delete, 추상클래스) (0) | 2022.11.21 |
| NestJS | production/development환경 각각 다른 DB 사용하기(dotenv) (2) | 2022.11.19 |
| NestJS | 패키지 버전 지정해서 세팅하기 (0) | 2022.11.19 |
| node.js | 인스타그램: 비밀번호 암호화(bcrypt) (1) | 2022.10.04 |