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?

NestJSでConfigModuleを使ってアプリで共通する定数を定義する方法

Posted at

NestJSのConfigModuleを使うことで、アプリケーション全体で使用する設定値や定数を一元管理できます。ここでは、ConfigModuleを使った設定管理の実装方法を解説します。

1. 必要なパッケージのインストール

yarn add @nestjs/config

2. 設定ファイルの作成

環境ごとに異なる設定値を定義する設定ファイルを作成します。

// config/database.config.ts
export default () => ({
  database: {
    host: process.env.DATABASE_HOST || 'localhost',
    port: parseInt(process.env.DATABASE_PORT, 10) || 5432,
    username: process.env.DATABASE_USERNAME || 'postgres',
    password: process.env.DATABASE_PASSWORD || 'password',
    database: process.env.DATABASE_NAME || 'mydb',
  },
});
// config/app.config.ts
export default () => ({
  port: parseInt(process.env.PORT, 10) || 3000,
  jwt: {
    secret: process.env.JWT_SECRET || 'secret',
    expiresIn: process.env.JWT_EXPIRES_IN || '1h',
  },
  redis: {
    host: process.env.REDIS_HOST || 'localhost',
    port: parseInt(process.env.REDIS_PORT, 10) || 6379,
  },
});

3. ConfigModuleの設定

AppModuleでConfigModuleを設定し、設定ファイルを読み込みます。

// app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import databaseConfig from './config/database.config';
import appConfig from './config/app.config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // グローバルモジュールとして設定
      load: [databaseConfig, appConfig], // 設定ファイルを読み込み
      envFilePath: '.env', // 環境変数ファイルのパス
    }),
  ],
})
export class AppModule {}

4. 設定値の利用

サービスやコントローラーで設定値を利用する方法です。

// sample.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class SampleService {
  constructor(private configService: ConfigService) {}

  getDatabaseConfig() {
    // 設定値を取得
    const dbHost = this.configService.get<string>('database.host');
    const dbPort = this.configService.get<number>('database.port');

    return {
      host: dbHost,
      port: dbPort,
    };
  }

  getJwtConfig() {
    // JWT設定を取得
    const jwtSecret = this.configService.get<string>('jwt.secret');
    const jwtExpiresIn = this.configService.get<string>('jwt.expiresIn');

    return {
      secret: jwtSecret,
      expiresIn: jwtExpiresIn,
    };
  }
}

5. 環境変数ファイルの例

.envファイルで環境変数を定義します。

# .env
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_USERNAME=postgres
DATABASE_PASSWORD=password
DATABASE_NAME=mydb

JWT_SECRET=my-secret-key
JWT_EXPIRES_IN=1h

REDIS_HOST=localhost
REDIS_PORT=6379

PORT=3000

6. まとめ

  • ConfigModuleを使うことで、アプリケーション全体で使用する設定値を一元管理できます。
  • 環境変数と設定ファイルを組み合わせることで、環境ごとに異なる設定も柔軟に管理できます。

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?