0

In order to apply the value of synchronize dynamically, the following code was written.

I executed the next cli

$ nest new project
$ npm i --save @nestjs/config

This is my code

/.env
# related to server
SERVER_MODE = dev
SERVER_PORT = 3000

# releated to DB
DB_TYPE = mysql
DB_HOST = localhost
DB_PORT = 3306
DB_USERNAME = root
DB_PASSWORD = test123
DB_DATABASE = testProject
/src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';

let syncBoolean = process.env.SERVER_MODE === 'dev' ? true : false
console.log(`SERVER_MODE:${process.env.SERVER_MODE}`) // I expected that value of process.env.SERVER_MODE will be true. but, It was undefined.
@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: process.env.DB_HOST,
      port: Number(process.env.DB_PORT),
      username: process.env.DB_USERNAME,
      password: process.env.DB_PASSWORD,
      database: 'slc_project',
      entities: [],
      synchronize: syncBoolean,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
console.log(`SERVER_MODE:${process.env.SERVER_MODE}`) // It works fine. it was dev

I found this fact that

like ConfigModule, Modules are made statically in nestjs. That's why, like controllers and services, you can only use configModule after all the applications have been created by the modules. In other words, The configModule cannot be used when the module is created.

The problem is that I don't know how to turn a module into a dynamic module.

I'd appreciate it if you could let me know the document for reference.

Ken White
  • 123,280
  • 14
  • 225
  • 444
ChangMin
  • 3
  • 2

1 Answers1

0

There are two solutions here:

  1. make import { config } from 'dotenv'; config() the first lne of your main.ts so that it populates process.env before anything else happens

or

  1. use the forRootAsync/registerAsync module loaders instead of forRoot/register so that you can use inject and useFactory to inject the ConfigService as shown in the docs
Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • i tried the first method, and it worked!!!! regarding to the second method, I gotta go to read the docs that you attached. I really appreciate everything you've done!! have a nice day :) – ChangMin Mar 05 '23 at 05:10