본문 바로가기

Development/TIL

NestJS_Configuration

설정(Configuration)이란?

소스 코드 안에서 어떤 코드들은 개발 환경이나 운영 환경에 따라 다르게 코드를 넣어줘야할 때가 있으며

노출되지 않아야하는 코드들도 있다. 그래서 설정 파일을 따로 만들어서 보관해야한다.

설정파일은 runtime 도중에 바뀌는 것이 아닌 애플리케이션이 시작할 때 로드가 되어서 그 값들을 정의해 준다.

그리고 XML, JSON, YAML, Environment Variables 같이 많은 형식을 이용할 수 있다.

 

Configuration을 위해 필요한 모듈

윈도우 기준

npm install -g win-node-env

npm install config --save

 

config 모듈을 이용한 설정 파일 생성

  • 루트 디렉토리에 config 폴더를 생성
  • config 폴더 안에 defalut.yml, development.yml, production.yml 파일 생성

 

defalut.yml 파일

: 기본설정(개발환경, 운영환경 모두 적용)

server: 
  port: 3000
  
db: 
  type: 'postgres'
  port: 5432
  database: 'dbname'

jwt:
  expiresIn: 3600

 

development.yml 파일

: defalut.yml + 개발 환경에서 필요한 정보

* 개발환경에서는 entity를 수정할 경우가 있으니 db와 동기화를 위해 synchronize를 true로 설정

db: 
  host: 'localhost'
  username: 'username'
  password: 'userpassword'
  synchronize: true


jwt: 
  secret: 'secretkey'

 

production.yml

: defalut.yml + 운영 환경에서 필요한 정보

* 운영환경에서는 entity가 수정되었을 때 중요한 데이터의 삭제를 대비해 synchronize를 false로 설정

db: 
  synchronize: false

 

 

Config 폴더 안에 저장된 것들을 사용하는 방법

config 모듈 import

예시 코드 - app.module.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger } from '@nestjs/common';
import * as config from 'config';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const serverConfig = config.get('server');
  const port = serverConfig.port

  await app.listen(port);
  Logger.log(`${port}번 포트로 서버가 열렸습니다.`)
}
bootstrap();

 

 

예시 코드 - typeorm.config.ts

import { TypeOrmModuleOptions } from "@nestjs/typeorm";
import * as config from "config";

const dbConfig = config.get('db');

export const typeORMConfig : TypeOrmModuleOptions = {
    type: dbConfig.type,
    host: process.env.RDS_HOSTNAME || dbConfig.host,
    port: process.env.RDS_PORT || dbConfig.port,
    username: process.env.RDS_USERNAME || dbConfig.username,
    password: process.env.RDS_PASSWORD || dbConfig.password,
    database: process.env.RDS_DB_NAME || dbConfig.database,
    entities: [__dirname + '/../**/*.entity.{js,ts}'],
    synchronize: dbConfig.synchronize
}

 

 

그리고 마지막으로 중요한 것은 gihub에 올릴 때 config 폴더에 있는 내용들이

올라가면 안되므로 gitignore에 추가해줘야 한다.

## 파일 무시
test.txt

## 다음과 같은 확장자는 전체 무시
*.text
*.exe
*.zip

## 폴더 무시
test/

 

제외되어야할 파일 또는 폴더를 이미 commit을 해버린 상황이라면

아래 명령어를 통해 cache를 지워줘야 한다.

## 파일 이라면
git rm --cached test.txt

## 전체파일 이라면
git rm --cached *.txt

## 폴더 라면
git rm --cached test/ -r

'Development > TIL' 카테고리의 다른 글

TypeORM Isolation Level  (0) 2023.05.30
Typeorm Transaction  (0) 2023.05.29
Nest.js (feat.Pipe)  (0) 2023.05.24
Nest.js(feat.DTO)  (0) 2023.05.22
기획 단계의 소통과 의사 결정에 대하여  (0) 2023.05.20