15

I use @UseInterceptors with FilesInterceptor from @nestjs/platform-express. FilesInterceptor allows me to pass some configs (like files storage folder). I would like to pass not exact values (e.g. 'public') but to get them from configService.

From this answer (https://stackoverflow.com/a/59828094/13128344) I understood why calling this.configService from UseInterceptors results in undefined.

@UseInterceptors(FilesInterceptor('cat_pic', 2, this.configService.get('storageConfigs')))

So how can I pass configs to FilesInterceptor? Or how to access a service if I move file interceptor function to a separate module?

  • 1
    I changed `ConfigModule` to use a fixed configuration object (it includes env and other variables). I require that object directly where I cannot access `configService` – Tatsiana Slabodchykava Aug 24 '20 at 07:19

1 Answers1

6

One option you have is to call config() from the dotenv package to load everything into process.env in your main.ts. You can still use the ConfigModule and ConfigService everywhere else, but in decorators you would use that process.env.storageConfigs variable.

Another option would be a package like @golevelup/profiguration which is a configuration service that can be used in decorators because of the way it was written.

Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • In Nest.js v9, if you include your decorator in the `providers` block for a module that has access to configService, you can then have the configService injected into your decorator with e.g. `constructor(protected readonly configService: ConfigService) {}` and use it as you would anywhere else. Wasn't very discoverable, hope this might help someone! – miek Feb 03 '23 at 13:04
  • 1
    @miek Just because that _class instance_ has access to the injected config service doesn't mean that decorators of that class will. It's very dependent on how the decorator is written, and in many cases, like `@UseInterceptors()` the `ConfigService` **can not** be accessed – Jay McDoniel Feb 03 '23 at 16:14
  • 1
    Oh, that’s unfortunate. Very much an YMMV thing, then. Thanks for the heads-up! – miek Feb 04 '23 at 17:36