nest.js 集成項(xiàng)目環(huán)境配置 env config

通過env搭配@nestjs/config實(shí)現(xiàn) 環(huán)境配置。

安裝依賴

$ yarn add @nestjs/config
$ yarn add cross-env -D 

文件配置

創(chuàng)建環(huán)境配置文件

# 環(huán)境變量文件夾
/env
# 默認(rèn)兜底配置
/env/.env
# 開發(fā)環(huán)境
/env/.env.development
# 本地環(huán)境
/env/.env.local
# 生產(chǎn)環(huán)境
/env/.env.production
# ts 配置對(duì)象
/config
# 默認(rèn)配置
/config/configuration.ts

config TS

/config/configuration.ts

/**
 * 函數(shù)運(yùn)行時(shí)區(qū)分env 變量不支持
 * @returns
 */
const findConfigModel = () => ({
  // 端口
  port: parseInt(process.env.PORT) || 8081,
  host: process.env.HOST,
  projectName: process.env.PROJECTNAME,
  // jwt secret
  jwtsecret: process.env.JWT_CONSTANTS,
  /**
   * 項(xiàng)目部署統(tǒng)一前綴
   */
  prefix: process.env.PREFIX,
  /**
   * 對(duì)稱加密的密鑰
   */
  signHmac: process.env.SIGN_HMAC,
});

/**
 * 默認(rèn)配置導(dǎo)出
 */
export default findConfigModel;

/**
 * 配置類型
 */
export type ConfigurationType = ReturnType<typeof findConfigModel>;


  • 修改 /src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import configuration from 'config/configuration';

// 環(huán)境變量加載
const envFilePath = ['env/.env'];
if (process.env.NODE_ENV) {
  envFilePath.unshift(`env/.env.${process.env.NODE_ENV}`);
}

@Module({
  imports: [
    ConfigModule.forRoot({
      load: [configuration],
      envFilePath,
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

main.ts 使用配置

const configService = app.get(ConfigService);
const value = configService.get('xxxx');
// 獲取環(huán)境變量
const dbUser = configService.get<string>('DATABASE_USER');

// 獲取自定義配置值
const dbHost = configService.get<string>('database.host');

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { Logger } from '@nestjs/common';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { ConfigurationType } from 'config/configuration';

async function bootstrap() {
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
  );

  const configService = app.get(ConfigService<ConfigurationType>);
  const PORT = configService.get('port');
  const HOST = configService.get('host');
  const PREFIX = `/${configService.get('prefix')}`;
  const PROJECTNAME = configService.get('projectName');
  const logger: Logger = new Logger('main.ts');

  app.setGlobalPrefix(PREFIX);

  await app.listen(PORT, HOST, () => {
    logger.log(
      `[${PROJECTNAME}]已經(jīng)啟動(dòng),接口請(qǐng)?jiān)L問: 
      http://${HOST}:${PORT}${PREFIX}
      http://${HOST}:${PORT}${PREFIX}/graphiql
      `,
    );
  });
}
bootstrap();

services 使用配置

  • module 引入-ConfigModule
  imports: [SequelizeModule.forFeature([UserModel]), ConfigModule],
  • 依賴注入
import { HttpService } from '@nestjs/axios';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectModel } from '@nestjs/sequelize';
import { AppJobModel } from 'src/model/customer/app-job.model';
import { IBaseService } from 'src/utils/base-service';
import { CONST_CONFIG } from 'src/utils/const-config';

@Injectable()
export class AppJobService extends IBaseService<AppJobModel> {
  constructor(
    @InjectModel(AppJobModel)
    private appJobModel: typeof AppJobModel,
    private readonly httpService: HttpService,
    private configService: ConfigService,
  ) {
    super();
  }
/**
   * 獲取java 任務(wù)信息
   * @param jobId
   */
  async queryJavaJob(jobId: string) {
    const url = `${this.configService.get<string>(
      CONST_CONFIG.JAVASERVERURL,
    )}/app-web/marketing/bee/task?taskCode=${jobId}`;
    return this.httpService.axiosRef
      .get(url)
      .then((res) => res.data)
      .catch((error) => {
        console.log(error);
        throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
      });
  }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容