#How to inject logger in non-injectable module or make it injectable and extendable?

8 messages · Page 1 of 1 (latest)

last pike
#

I have a HttpService which is not injectable. It implements basic methods such as get, post etc and receives baseUrl as constructor argument to then create axios instance:

export class HttpService {
  #instance: AxiosInstance;

  constructor(baseURL: string) {
    this.#instance = axios.create({ baseURL });
  }
}

Then I can create new more specific http client based in HttpService:

export class DreamClient extends HttpService  {
  constructor(private readonly configService: ConfigService) {
    super(configService.DREAM_URL.toString());
  }
}

But now I want to add request and response interceptors in my base HttpService to be able to log outgoing requests. For that I need to inject winston logger which I cannot do since HttpService is not injectable. How can I make HttpService injectable (to be able to inject logger directly) while keeping extendability (to avoid passing down baseURL in every method)?

civic ermine
#

Why not make the http service injectable in the first place?

last pike
#

I can make it injectable, but I want to avoid passing down baseUrl in methods each time I make a call.

civic ermine
#

You can still inject the url by using a custom provider

last pike
#

That's what I was wondering about. It seems like custom provider would not be enough for this. My vision of how it should be implemented is very similar to how modules built for NestJS:

MyModule.forRootAsync({
  imports: [ConfigModule],
  useFactory: (configService: ConfigService) => ({
    baseURL: configService.BASE_URL,
  }),
  inject: [ConfigService],
}),

But I don't need to do this for an entire module at the top level at app.module.ts. I would rather do it wherever HttpClient service is imported as a dependency module. But documentation doesn't cover such cases. It only has an example of how to pass options via forRoot or register. Thus I'm not entirely sure what exactly to choose - dynamic module or custom provider.

#

Unless I'm missing something.

civic ermine
#

Does this url change per injection of the HttpService?

last pike
#

Yes. I expect there will be more than one service depending on it.