noamtm
noamtm

Reputation: 12983

Pass value to a NestJS service

In my NestJS app, I have a service that is used for performing HTTP requests with a vendor (acting as a client library for that vendor). The service needs an API key, which is available as an env var VENDOR_API_KEY.

For unit tests, I want to use another, hardcoded value for the API key - instead of taking it from VENDOR_API_KEY.

What is the idiomatic way of doing it? All of the options given in https://docs.nestjs.com/fundamentals/custom-providers seem like overkill.

I might be missing something obvious because I'm new to NestJS.

Upvotes: 0

Views: 1765

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70550

Sounds like you'd need a very simple custom provider. Something as quick as

@Module({
  providers: [
    ServiceToBeUsed,
    {
      provide: 'API_KEY',
      useValue: process.env.VENDOR_API_KEY, //you could also use a factory and inject the config service
    }
  ]
})
export class SomeModule {}

And now you can use @Inject('API_KEY') private readonly apiKey: string in your service's constructor

Upvotes: 2

Related Questions