Created
December 7, 2022 15:46
-
-
Save matiasgarcia/53d2aa20acecec511b285efd86525279 to your computer and use it in GitHub Desktop.
interceptor nestjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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