nestjs: config 配置

在实际项目中使用 config 模块
更新于: 2023-12-26 17:45:18

安装

yarn add @nestjs/config

添加 Config Module 

文件为 app.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot(),
  ],
})
export class AppModule {}

使用

文件为 main.ts 这个 config 会自动加载 .env 文件里的配置信息

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(process.env.PORT ? parseInt(process.env.PORT) : 3000);
}
bootstrap();

自定义配置

文件为: config/configuartion.ts

export default () => ({
  port: parseInt(process.env.PORT) || 3000,
  pokemonService: {
    apiKey: process.env.POKEMEON_KEY,
  }
});

加载配置,使用 load 这个 key 来完成加载。

isGlobal 可以让 ConfigModule 到处都是,不过,在单 module 应用里,貌似不需要?

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import config from './config/configuration';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [config]
    }),
  ],
})
export class AppModule {}

多个配置

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import base from './config/base.config';
import database from './config/database.config';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [base, database] // split your configuration files into separate files
    }),
  ],
})
export class AppModule {}

注入使用

重点是这一句:private readonly configService: ConfigService

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class FeatureService {

  constructor(private readonly configService: ConfigService) {}

  someFunction(param: string) {
    const port = this.configService.get<number>('port');
      // ...
  }

  someOtherFunction(param: string) {
    const pokemonAPIKey = this.configService.get<string>('pokemonService.apiKey');
      // ...
  }
}

项目实战

功能代码
.env 加载顺序
// src/app.controller.ts

import { Module } from '@nestjs/common';
import { CacheModule } from '@nestjs/cache-manager';
import * as redisStore from 'cache-manager-redis-store';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import configPages from './config/pages';

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: ['.env', '.env.local'],
      load: [configPages]
    }),
    CacheModule.registerAsync({
      useFactory: () => {
        const { REDIS_HOST, REDIS_PORT, REDIS_USERNAME, REDIS_PASSWORD, REDIS_DB_NO } = process.env;
        return {
          store: redisStore,
          host: REDIS_HOST,
          port: REDIS_PORT,
          username: REDIS_USERNAME,
          password: REDIS_PASSWORD,
          db: REDIS_DB_NO,
          ttl: 60 * 60 * 24 * 365
        };
      }
    })
  ],
  controllers: [AppController],
  providers: [AppService]
})
export class AppModule {}
配置文件
// src/config/pages.ts

export default () => ({
  home: {
    maxSubCategory: 5
  }
});

参考