app.module.ts
@Module({
imports: [ConfigModule(), BoardModule],
controllers: [AppController],
providers: [AppService],
})
config/configuration.ts
export default () => ({
ENVIRONMENT: process.env.DEVELOPMENT,
});
config/index.ts
import { ConfigModule } from '@nestjs/config';
import configuration from './configuration';
export default ({} = {}) =>
ConfigModule.forRoot({
// 전역으로 사용하는지?
isGlobal: true,
// env 파일 경로 지정
envFilePath: `.env.local`,
// 어떤 환경 변수를 불러올 것인가?
load: [configuration],
});
.env.local
ENVIRONMENT = Development
app.module.ts
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
TypeOrmModule.forRootAsync({
//env 파일을 불러오기 위한 import
imports: [ConfigModule],
//config 불러오기
useClass: typeORMConfig,
}),
this.config.Service.get을 통해 환경 변수 데이터 불러오기
import { ConfigService } from '@nestjs/config';
import { TypeOrmOptionsFactory, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { Injectable } from '@nestjs/common';
@Injectable()
export class typeORMConfig implements TypeOrmOptionsFactory {
constructor(private configService: ConfigService) {}
createTypeOrmOptions(): TypeOrmModuleOptions | Promise<TypeOrmModuleOptions> {
return {
type: 'postgres',
host: this.configService.get('DB_HOST'),
port: this.configService.get<number>('DB_PORT'),
username: this.configService.get('DB_USER'),
password: this.configService.get('DB_PASSWORD'),
database: this.configService.get('DB_DATABASE'),
entities: [__dirname + '../**/*.entity.{.ts,.js}'],
ssl: {
rejectUnauthorized: false,
},
synchronize: false, //entity가 변할 때 변한 값을 실제 DB에 반영하겠냐는 조건 (실제 프로덕션 환경에서는 끄는게 좋다.)
logging: true,
};
}
}