[Nest.js] 개발/운영 환경별 config 설정

Woong·2022년 11월 24일
1

Nestjs

목록 보기
6/28

설치

npm install @nestjs/config

적용

  • AppModule 에서 global 로 사용하도록 정의
    • .env 에 정의된 key/value 환경변수를 process.env 에 할당하고 ConfigService 를 통해 접근할 수 있다.
    • 런타임에서 정의한 환경변수도 접근 가능 (런타임 쪽이 우선순위 높음)
import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'

@Module({
  imports: [ConfigModule.forRoot({ isGlobal: true})],
})
export class AppModule {}
  • ConfigModule 을 import 하여 .env 에 정의된 환경변수를 불러올 수 있다.
import { Module } from '@nestjs/common'
import { ConfigModule } from '@nestjs/config'

@Module({
  imports: [ConfigModule, ...],
  providers: [...],
  controllder: [...]
 })
export class MyModule { }
  • 프로바이더에서는 ConfigService 를 주입받아 환경변수 접근
@Injectable()
export class MyService {
  constructor(private readonly configService: ConfigService) { }
  
  async test() {
    const baseDir = this.configService.get<string>('BASE_DIR')
    console.log(baseDir)
  }
}
  • main.ts 에선 app.get(ConfigService) 를 통해 ConfigService 를 사용할 수 있다.
async function bootstrap() {
  const app = await NestFactory.create(AppModule)

  const configService = app.get(ConfigService)
  const port = configService.get('NODE_SERVER_PORT')
  await app.listen(port)
}
bootstrap()
  • 데코레이터에선 useFactory 를 통해서 사용할 수 있다.
import { Module } from '@nestjs/common'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { MongooseModule } from '@nestjs/mongoose'

@Module({
  imports : [
    MongooseModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        uri: configService.get<string>('MONGODB_URL'),
      }),
      inject: [ConfigService],
    }),
  ]
})
export class MongoConnectorModule { }

reference

0개의 댓글