#[node] 환경변수 2탄

2025. 1. 23. 14:24개발/Node

2025.01.22

9.8 YAML 파일을 사용해 환경 변수 설정

9.8.1 js-yaml 설치

npm i js-yaml
npm i -D @types/js-yaml
# yaml
http: 
  port: 3000


redis: 
  host: 'localhost'
  port: 6379

9.8.3 config.ts 수정

(1) yaml 파일 커스텀 설정 파일로 취급. conifg.ts 에 설정 추가


import { readFileSync } from "fs";
import * as yaml from 'js-yaml'
// YAML file loading
const yamlConfig: Record<string,any> = yaml.load(
    readFileSync(`${process.cwd()}/src/envs/config.yaml`, 'utf-8'),
)
//(생략)
export default () => ({
    ...common,
    ...conf,
    ...yamlConfig // yaml 설정 
})

9.8.4 테스트용 핸들러 함수로 테스트

(1) app.controller.ts

  // 핸들러 함수 테스트 
  @Get('redis-info')
  getRedisInfo() : string {
    return `${this.configService.get('redis.host')}:${this.configService.get('redis.port')}`
  }

9.9 캐시 옵션 사용

(1) 캐시를 사용하여 환경 설정을 사용하도록 함.

설정파일 읽고 내용을 파싱해 메모리에 키와 값으로 저장해야 사용가능.
설정 파일은 서버가 한번 가동뒤에는 변경 디지 않음 -> 캐시 사용하면 성능에서 이득
캐시를 사용할수 있게 옵션을 수정

//app.module.ts
@Module({
  imports: [
    ConfigModule.forRoot({ 
      isGlobal: true,
      envFilePath : `../envs/${process.env.NODE_ENV}.env`,
      // ignoreEnvFile : false,
      // load 옵션을 사용해 커스텀 설정 파일 추가 
      load: [config],
      cache : true
    }),

9.10 확장 변수 사용

(1) 확장변수는 이미 선언된 변수를 다른벼수 ${변수명} 으로 할당하는 기능

src/envs/local.env

SERVER_DOMAIN = localhost
SERVER_PORT = 3000
SERVER_URL = http://${SERVER_DOMAIN}:${SERVER_PORT}

9.10.1 확장 변수 사용할수 있게 추가 설정

// app.module.ts
@Module({
  imports: [
    ConfigModule.forRoot({ 
      cache : true, // 캣시 허용 
      expandVariables: true // 확장변수 옵션 추가 

9.10.2 테스트용 핸들러 함수로 테스트

  @Get('service-url')
  getServiceUrl() :string {
    console.log( this.configService.get('SERVICE_URL'))
    return  this.configService.get('SERVICE_URL')
  }

9.11 main.ts 에서 환경변수 사용

  • main.ts 는 express 에서 index.js 같은 역할을 함. 가장 먼저 실행되므로 NestFactory.create()를 호출하기 전에는 ConfigModule이 활성화 되지 ㅇ낳음.
  • 클래스도 없고 bootstrap() 함수마 ㄴ있어서 기존처럼 클래스 생성자로 의존성 주입을 받을 수 없음.
  • 다른 방법으로 ConfigService 를 사용해야함. app.get() 메서드에 ConfigSerice 클래스를 인수로 주고 반환값을 받는 방식 사용