0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【NestJS】環境変数を設定してグローバルモジュールで読み込む方法

Last updated at Posted at 2022-03-17

概要

環境変数を設定して各モジュールで読み込む方法をまとめる

依存関係をインストール

npm i --save @nestjs/config

カスタム構成ファイルを定義

config/configuration.ts
export default () => ({
  nodeEnv: process.env.NODE_ENV || 'development',
  server: {
    port: parseInt(process.env.PORT) || 3000,
    hostName: process.env.hostname || 'localhost:3000',
  },
  database: {
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT) || 5432,
    user: process.env.DB_USERNAME || 'root',
    pass: process.env.DB_PASSWORD || 'password',
    name: process.env.DB_NAME || 'sample',
  },
  auth: {
    jwt_secret_key:
      'Bearer xxxxx',
    hashSalt: 10,
  },
})

メインモジュールで読み込む

src/app.module.ts
@Module({
  imports: [
    ConfigModule.forRoot({
      // グルーバルモジュールにする
      isGlobal: true,
      
      // カスタム構成ファイルを読み込み 
      load: [configuration],
    }),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.get('database.host'),
        port: Number(configService.get('database.port')),
        username: configService.get('database.user'),
        password: configService.get('database.pass'),
        database: configService.get('database.name'),
        entities: [join(__dirname + '/domain/entities/*.entity{.ts,.js}')],
        extra: {},
      }),
      inject: [ConfigService],
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware, OemSettingMiddleware).forRoutes('')
  }
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?