Samuel Levy
Samuel Levy

Reputation: 87

How can I make a request for two different domains in the same module in NestJs?

Today we have two different domains in our ecosystem. Our BFF should receive informations from those different endpoints.

If I add FirstService and SecondService in providers, both services get the same informations in HttpModule.registerAsync, but I must have two different baseUrl

Module.ts

@Module({
  imports: [
    HttpModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        timeout: 5000,
        maxRedirects: 5,
        baseURL: configService.get('SERVICE_URL_LEGACY'),
      }),
    }),
  ],
  providers: [FirstService, SecondService],
  controllers: [CampaignsController],
})
export class CampaignsModule {}

Controller must be something like this

Controller

export class CampaignsController {
  constructor(
    private readonly firstService: FirstService,
    private readonly secondService: SecondService,
  ) {}

  @Get('/review')
  async getReview() {
    const response = await this.firstService.getReview({});
    const responseTwo = await this.secondService.getReview({});
  }

Upvotes: 1

Views: 2041

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187232

There's only ever going to be one HttpModule in CampaignsModule, and it would have no way to know which service invoked it.

If FirstService and SecondService were in different modules, you could work. configure an HttpModule for each one with the right settings. But that may not be right for you.

Otherwise you'd just have to send the baseURL in each time you use the HttpService like:

@Injectable()
export class FirstService {
  constructor(
    private readonly http: HttpService,
    config: ConfigService,
  ) {
    this.baseURL = config.get('SERVICE_URL_LEGACY')
  }

  async getReview() {
    return this.httpService.get('/whatever', { baseURL: this.baseURL }) 
  }
}

Upvotes: 1

Related Questions