2

My nestjs system is a system that connects to multiple systems via API calls.

For each system, I created a Module to handle their processes. Each of these modules imports HttpModule.

I want to have separate Axios interceptors for each of these modules' HttpModule.

This is my attempt to test the functionality:

on a.module.ts:

@Module({
  imports: [
    HttpModule,
    // Other imports
  ],
  // controllers, providers and exports here
})
export class ModuleA implements OnModuleInit {
  constructor(private readonly httpService: HttpService) { }
  public onModuleInit() {
    this.httpService.axiosRef.interceptors.request.use(async (config: Axios.AxiosRequestConfig) => {
      console.log('Module A Interceptor');    
      return config;
    });
  }
}

The module class for Module B is similar, with a different message in the console.log call.

I tried making a http call to System B using a service in Module B, but both messages are displayed in the console.

I figured that the http module is a singleton across the system, so how do I instantiate a separate HttpModule for Module A and Module B?

Edwin
  • 886
  • 2
  • 13
  • 32

1 Answers1

4

After reading the documentation on Dynamic Modules and this bug report, it turns out that calling the register() method in the import creates a separate instance of the HttpModule.

So my solution is to call the register() and pass in an empty object on both Module's @Module declaration.

@Module({
  imports: [
    HttpModule.register({}),
  ],
  // providers and exports
})

I'm not sure if this is the correct way of doing it, but it seems to work.

Edwin
  • 886
  • 2
  • 13
  • 32