我正在尝试在 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();