0

我正在尝试在 nestjs/bull 模块的 @Process() 装饰器中使用环境变量值,如下所示。我应该如何提供“STAGE”变量作为工作名称的一部分?

import { Process, Processor } from '@nestjs/bull';
import { Inject } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Job } from 'bull';

@Processor('main')
export class MqListener {

  constructor(
    @Inject(ConfigService) private configService: ConfigService<SuperRootConfig>,
  ) { }

  // The reference to configService is not actually allowed here:
  @Process(`testjobs:${this.configService.get('STAGE')}`)
  
  handleTestMessage(job: Job) {
    console.log("Message received: ", job.data)
  }
}

编辑了 Micael 和 Jay 的答案(如下):

Micael Levi 回答了最初的问题:您不能使用 NestJS ConfigModule 将您的配置放入内存变量中。但是,在引导函数中运行 dotenv.config() 也不起作用;如果您尝试从方法装饰器中访问它们,您将获得未定义的内存变量值。为了解决这个问题,Jay McDoniel 指出您必须在导入 AppModule 之前导入文件。所以这有效:

// main.ts
import { NestFactory } from '@nestjs/core';
require('dotenv').config()
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(process.env.PORT || 4500);
}
bootstrap();

4

1 回答 1

2

this由于装饰器评估的工作方式,您不能在该上下文中使用。那时,没有为MqListener类创建实例,因此,使用this.configService没有意义。

您需要process.env.直接访问。因此将dotenv在该文件中调用(或读取和解析您的 dot env 文件的库)。

于 2021-12-28T02:47:12.350 回答