- nestjs - configuration 공식문서 : https://docs.nestjs.com/techniques/configuration
ConfigModule 설치
npm i --save @nestjs/config
환경설정
export interface ConfigModuleOptions { /** * If "true", values from the process.env object will be cached in the memory. * This improves the overall application performance. * See: https://github.com/nodejs/node/issues/3104 */ cache?: boolean; /** * If "true", registers `ConfigModule` as a global module. * See: https://docs.nestjs.com/modules#global-modules */ isGlobal?: boolean; // 어디서나 접근할 수 있도록 /** * If "true", environment files (`.env`) will be ignored. */ ignoreEnvFile?: boolean; /** * If "true", predefined environment variables will not be validated. */ ignoreEnvVars?: boolean; /** * Path to the environment file(s) to be loaded. */ envFilePath?: string | string[]; /** * Custom function to validate environment variables. It takes an object containing environment * variables as input and outputs validated environment variables. * If exception is thrown in the function it would prevent the application from bootstrapping. * Also, environment variables can be edited through this function, changes * will be reflected in the process.env object. */ validate?: (config: Record<string, any>) => Record<string, any>; /** * Environment variables validation schema (Joi). */ validationSchema?: any; /** * Schema validation options. * See: https://joi.dev/api/?v=17.3.0#anyvalidatevalue-options */ validationOptions?: Record<string, any>; /** * Array of custom configuration files to be loaded. * See: https://docs.nestjs.com/techniques/configuration */ load?: Array<ConfigFactory>; /** * A boolean value indicating the use of expanded variables, or object * containing options to pass to dotenv-expand. * If .env contains expanded variables, they'll only be parsed if * this property is set to true. */ expandVariables?: boolean | DotenvExpandOptions; }
Corss-Env 설치
npm i cross-env
cross-env 환경변수 지정 방법
cross-env 환경변수명1=환경변수값1 환경변수명2=환경변수값2 …
{ "scripts": { "build": "cross-env FIRST_ENV=one SECOND_ENV=two node ./my-program" } }

TypeOrmModule에서 사용하는 procee.env.환경변수 값들은 .env.dev 별도의 env 파일로 분리해둔 곳에서 가져오는 값으로 구성했다.
환경변수 유효성 검증
ConfigureModuleOption
중에 validationSchema
이라는 옵션이 있는데, 이걸로 환경변수의 유효성을 검사할 수 있다.명시된 환경변수들이 준비되지 않았으면 앱이 실행되지 않도록 할 수 있다.
joi
가장 강력한 자바스크립트
schema description language
이자, 데이터 검증 툴이다.# joi 라이브러리 설치 npm i joi
유효성 설정

유효성 검증(에러)
required()
라고 명시했는데 env
에 포함되지 않았을 경우 에러를 띄워준다.