簡體   English   中英

如何在 NestJs 的同一個模塊中請求兩個不同的域?

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

今天,我們的生態系統中有兩個不同的領域。 我們的 BFF 應該從這些不同的端點接收信息。

如果我在providers中添加FirstServiceSecondService ,這兩個服務在HttpModule.registerAsync中獲得相同的信息,但我必須有兩個不同的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

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({});
  }

CampaignsModule中只會有一個HttpModule ,並且它無法知道哪個服務調用了它。

如果FirstServiceSecondService在不同的模塊中,你可以工作。 使用正確的設置為每個配置一個HttpModule 但這可能不適合您。

否則,您只需在每次使用HttpService時發送baseURL ,例如:

@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 }) 
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM