2

I am building a nestJs application, with scheduling and configuration. I want to be able to configure my Cron with my environment variable but it does not seems to work.

app.module.ts :

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

scheduling.service.ts (from my SchedulingModule) :

@Cron(process.env.CRON_VALUE)
scheduledJob() {
  this.logger.log('Scheduled : Job');
  ...
}

.env :

...
CRON_VALUE=0 4 * * *
...

Apparently at the moment the value is checked it's empty. I got the following error :

(node:55016) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_isAMomentObject' of undefined
    at new CronTime (/Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/cron/lib/cron.js:42:50)
    at new CronJob (/Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/cron/lib/cron.js:527:19)
    at /Users/antoinegrenard/Documents/Projet/b4finance/service-scheduling/node_modules/@nestjs/schedule/dist/scheduler.orchestrator.js:56:29 
    ...
Antoine Grenard
  • 1,712
  • 3
  • 21
  • 41
  • Does this answer your question? [How to pass configs from config service to Nest.js decorator?](https://stackoverflow.com/questions/63376082/how-to-pass-configs-from-config-service-to-nest-js-decorator) – HMilbradt Oct 06 '21 at 15:01

2 Answers2

6

Apparently it is not possible to get env values in decorators.

I had to do it this way :

constructor(private schedulerRegistry: SchedulerRegistry) {}

onModuleInit() {
  const job = new CronJob(process.env. CRON_VALUE, () => {
    // What you want to do here
  });

  this.schedulerRegistry.addCronJob(name, job);
  job.start();
}
Antoine Grenard
  • 1,712
  • 3
  • 21
  • 41
1

To fix this problem you should load the config on your service again:

require('dotenv').config();
Youba
  • 2,636
  • 3
  • 11
  • 25
  • Is there a "nestjs" way to do that ? – Antoine Grenard Oct 06 '21 at 12:49
  • 1
    @Youba Unfortunately there is not, this is a limitation of its Config system because it evaluates `.env` AFTER all the imports and decorators are resolved. You have to manually ensure that .env is populated before other files are imported in order to have dynamic decorator values – Jesse Carter Oct 06 '21 at 14:46
  • Yes, you can't either pass a value from config service to a decorators, moreover you can't load the config from main.js when we working with Crons – Youba Oct 06 '21 at 15:09
  • I hope at least this solution works for you ^^ – Youba Oct 06 '21 at 15:09
  • @Youba what about from your app.module? – FooBar Jan 04 '22 at 20:09
  • @Youba Thanks for sharing your solution. That's what I ended up doing; adding it into app.module.ts (so that it will also work doing testing). I am amazed by Nest.js and how fun it most of the time is to work with, however, equally amazed at how "dumb" they made the ConfigModule. – FooBar Jan 04 '22 at 20:13