Search code examples
typescriptdependency-injectionnestjsmonorepotypescript-decorator

How to change NestJS Decorator string parameter when importing library


I have a NestJs monorepo with some Apps (microservices) and Libs. I have a Service class that I use in all my apps, so I wanted to extract it in a lib.

I thought it's good idea, but then I realized, I have a decorator on a method of this class, that needs a different const string for every app. Seems I'm not able to achieve that... Is there any way? Basically I would need to "inject" a const string from the loading app into the lib to be used by the decorator.

To be more specific, the decorator is a @RabbitSubscribe() (from golevelup/nestjs-rabbitmq), and the queue name (const string parameter for the decorator) needs to be different for each module.

But more generically, if I have this class in a lib:

@Injectable()
export class MyService {
  @ADecorator({
    param: 'this is the string',
  })
  myFunction() { ... }
}

How can I import it in different Apps, with a different string param for each app?


Solution

  • Disclaimer: I'm the author of @golevelup/nestjs-rabbitmq.

    The official configuration module for NestJS can only be instantiated once the DI system for NestJS is bootstrapped. For this reason, it's impossible to dynamically configure a decorator using this module.

    To work around this issue (and a few others including better type saftey) I built an alternative configuration package that works with ENV and .env files to help you configure your app(s). Using this package it's possible to bootstrap your app configuration before NestJS DI and any files including Decorators are imported so you could write code like:

    @Injectable()
    export class MyService {
      @ADecorator({
        param: config.queueName,
      })
      myFunction() { ... }
    }
    

    Where config.queueName could be retrieved differently in each app instance based on an ENV value or loaded from a .env or .json file