In my application Im calling third parts APIs via HttpService with axios, I want to implement a interceptor where that I can log all the request urls that passing trough the httpService.
import { HttpModule as AxiosHttpModule, HttpService } from '@nestjs/axios';
import { Global, Module, OnModuleInit } from '@nestjs/common';
import { AxiosError, AxiosResponse } from 'axios';
@Global()
@Module({
imports: [AxiosHttpModule],
exports: [AxiosHttpModule],
})
export class HttpModule extends AxiosHttpModule implements OnModuleInit {
constructor(private readonly httpService: HttpService) {
super();
}
public onModuleInit(): any {
const axios = this.httpService.axiosRef;
axios.interceptors.request.use(
(config) => {
console.log(`Request URL: ${config.url}`);
console.log(`Request Method: ${config.method}`);
return config;
},
(error: AxiosError) => {
console.error('Request Error:', error);
return Promise.reject(error);
},
);
axios.interceptors.response.use(
(response: AxiosResponse) => {
console.log('Response:', response.data);
return response;
},
(error: AxiosError) => {
console.error('Response Error:', error.response?.data);
return Promise.reject(error);
},
);
}
}
And I imported it in appmodule
HttpModule.registerAsync({
useFactory: (configService: ConfigService) => {
return {
timeout: 20000,
baseURL: configService.getOrThrow('BASE_URL'),
headers: {
'Content-Type': 'application/json',
},
};
},
inject: [ConfigService],
global: true,
}),
But the request logging is not working, I cannot figure out why.
Any help would be greatly appreciated.