Skip to content

Instantly share code, notes, and snippets.

@matiasgarcia
Created December 7, 2022 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matiasgarcia/53d2aa20acecec511b285efd86525279 to your computer and use it in GitHub Desktop.
Save matiasgarcia/53d2aa20acecec511b285efd86525279 to your computer and use it in GitHub Desktop.
interceptor nestjs
//http-client.module.ts
import { Module } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios';
import { HttpClientService } from './http-client.service';
@Module({
imports: [
HttpModule.register({
timeout: 20000,
maxRedirects: 5,
}),
],
providers: [HttpClientService],
exports: [HttpClientService],
})
export class HttpClientModule {}
//http-client.service.ts
import { HttpService } from '@nestjs/axios';
import { Injectable, Logger } from '@nestjs/common';
import { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Observable } from 'rxjs';
@Injectable()
export class HttpClientService {
private readonly logger = new Logger(HttpClientService.name);
public axiosRef: HttpService['axiosRef'];
constructor(private readonly httpService: HttpService) {
this.axiosRef = httpService.axiosRef;
this.httpService.axiosRef.interceptors.response.use(
(response) => {
const { status, config } = response;
const { url } = config;
this.logger.debug({
type: 'response',
url,
status,
});
return response;
},
(err) => {
if (err.response) {
const response = err.response;
const { status, config, data } = response;
const { url } = config;
this.logger.error({
type: 'response',
url,
status,
data,
});
} else if (err.request) {
this.logger.error({
type: 'request',
url: err.request.config.url,
err: err.message,
});
} else {
this.logger.error({
type: 'unknown',
err: err,
});
}
return Promise.reject(err);
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment