[NestJS] 환경 변수 관리하기

Younghwan Cha·2023년 3월 7일
0

Nest.js

목록 보기
13/27
post-thumbnail

A good approach for using this technique in Nest is to create a ConfigModule that exposes a ConfigService which loads the appropriate .env file. While you may choose to write such a module yourself, for convenience Nest provides the @nestjs/config package out-of-the box. We'll cover this package in the current chapter.

먼저, dependency 를 다운로드 받는다.

$ npm i @nestjs/config

@nestjs/config 는 내부적으로 dotenv 를 사용한다

이후에는 app.module.tsConfigModule 을 추가해준다

// app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

ConfigModule.forRoot().env 를 parse 하고 isGlobal: true 를 통해서 다른 모듈들이 ConfigModule 에 접근 할 수 있도록 한다.

postgres TypeORM 을 예시로 확인해보자

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { EndpointsModule } from './endpoints/endpoints.module';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        type: 'postgres',
        host: configService.get('DB_HOST'),
        port: +configService.get<number>('DB_PORT'),
        username: configService.get('DB_USERNAME'),
        password: configService.get('DB_PASSWORD'),
        database: configService.get('DB_NAME'),
        entities: [
          Endpoint
        ],
        synchronize: true,
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

이후에는 private readonly confingService: ConfigService 로 import 해서 아래와 같이 불러 올 수 있다.
this.confingService.get(<config_key>);

[nestjs config] https://docs.nestjs.com/techniques/configuration

profile
개발 기록

0개의 댓글