애플리케이션의 설정은 배포시 상황 ( 프로덕션, 개발, 로컬)에 따라 달라질 수 있습니다.
이때 환경변수를 상황에 맞게 저장을 해두는 것이 좋습니다.
.env (.env.local, .env.dev, .env.prod) 라는 곳에 저장된 변수들을 불러오는 방법은 아래와 같습니다.
설치
$ npm i --save @nestjs/config
예시
//package.json
{
...
"scripts": {
...
"start:local": "NODE_ENV=local nest start --watch",
...
},
...
}
// app.module.ts
import * as dotenv from 'dotenv';
dotenv.config();
import { ConfigModule, ConfigService } from '@nestjs/config';
import * as Joi from 'joi';
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { SnakeNamingStrategy } from 'typeorm-naming-strategies';
@Module({
imports: [
ConfigModule.forRoot({
validationSchema: Joi.object({
NODE_ENV: Joi.string().valid('dev', 'prod', 'local', 'debug').default('local'),
}),
isGlobal: true,
envFilePath: `.env.${process.env.NODE_ENV}`,
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'mysql',
host: configService.get<string>('DB_HOST'),
port: configService.get<number>('DB_HOST'),
username: configService.get<string>('DB_USERNAME'),
password: configService.get<string>('DB_PASSWORD'),
database: configService.get<string>('DB_NAME'),
autoLoadEntities: true,
synchronize: true,
logging: true,
namingStrategy: new SnakeNamingStrategy(),
}),
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config'; // import
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
// .env.local 에 있는 변수 호출
await app.listen(configService.get<number>('PORT'), configService.get<string>('HOST_IP'));
console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
터미널에서 실행 방법
$ npm run start:local
'프로그래밍 > Nest.js' 카테고리의 다른 글
[ Nest.js ] Logger 구현 (0) | 2024.06.26 |
---|---|
[ NestJS ] Jest 의 기본 사용법 (0) | 2024.06.14 |
[ NestJS ] build 를 이용하여 배포하는 이유 (0) | 2024.06.02 |
[ NestJS ] Configuration : Schema validation - Joi 예시 (0) | 2024.05.28 |
[ NestJS ] LocalStrategy 구현 중 겪은 문제 해결사항 기록 (0) | 2024.05.28 |