0

I'm trying to use an environment variable value in the nestjs/bull module's @Process() decorator, as follows. How should I provide the 'STAGE' variable as part of the job name?

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)
  }
}

EDITED with answers (below) from Micael and Jay:

Micael Levi answered the initial question: You can't use the NestJS ConfigModule to get your config into a memory variable. However, running dotenv.config() in your bootstrap function will not work either; you get undefined values for the memory variables if you try to access them from within a Method Decorator. To resolve this, Jay McDoniel points out that you have to import the file before you import AppModule. So this works:

// 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();

Can Rau
  • 3,130
  • 1
  • 23
  • 33
Aadmaa
  • 829
  • 5
  • 13

1 Answers1

2

You cannot use this on that context due to how decorator evaluation works. At that time, there's no instance created for MqListener class, thus, using this.configService doens't make sense.

You'll need to access process.env. directly. And so will call dotenv (or what lib that read & parses your dot env file) in that file.

Micael Levi
  • 5,054
  • 2
  • 16
  • 27
  • Thx. I have tried accessing process.env directly but the value is undefined when it is called. In addition to being loaded through ConfigService (not useful it seems), I also tried loading it with dotenv.config() in main.ts, upon startup, just prior to app.listen(). The value is still undefined: @Process(`${process.env.STAGE}`) is passed undefined. Am I missing something? – Aadmaa Dec 28 '21 at 04:09
  • 1
    Did you call `dotenv.config()` **before** importing the `app.module` file? Order is important here – Jay McDoniel Dec 28 '21 at 06:31