How to initialize on nestjs module multiple times with different configurations?

Viewed 930

How can I create two or multiple instances of a nestjs module? E.g. we would like to have two different instances of the TwilioModule and use different configurations for them.

import { TwilioModule } from 'nestjs-twilio';

@Module({
  imports: [
    TwilioModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (cfg: ConfigService) => ({
        accountSid: cfg.get('TWILIO_ACCOUNT_SID'),
        authToken: cfg.get('TWILIO_AUTH_TOKEN'),
      }),
      inject: [ConfigService],
    }),
    TwilioModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (cfg: ConfigService) => ({
        accountSid: cfg.get('TWILIO_ACCOUNT_SID_2'),
        authToken: cfg.get('TWILIO_AUTH_TOKEN_2'),
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}
1 Answers

Hey for this the package needs to have this feature. I recommend this.

import { Twilio } from 'twilio';
providers: [
 {
  provide: 'twilio1',
  useFactory: () => {
    return new Twilio('ACasd', 'wasdsa');
  },
},
{
  provide: 'twilio2',
  useFactory: () => {
    return new Twilio('ACasd', 'wasdsa');
  },
},
]



Use the following in the controller or in service

@Inject("twilio1") t1 : Twilio

Example:-

constructor(@Inject('twilo1') t1: Twilio) {}

read more @ https://docs.nestjs.com/fundamentals/custom-providers#factory-providers-usefactory

Related