To use the Node.js Axios library for making HTTP requests with automatic retries in Nest.js, you can integrate Axios with Nest.js and then utilize Axios' built-in retry functionality along with Nest.js' features. Here's how you can achieve this:
Install Axios: First, make sure you have Axios installed in your Nest.js project. If not, you can install it using npm or yarn:
npm install axios
or
csharpyarn add axios
Create a RetryInterceptor: Nest.js allows you to create interceptors to intercept and modify requests and responses. We'll create a custom interceptor to handle automatic retries using Axios.
typescript// retry.interceptor.ts
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, BadGatewayException } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';
import { catchError, retryWhen, mergeMap } from 'rxjs/operators';
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
@Injectable()
export class RetryInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
retryWhen(errors =>
errors.pipe(
mergeMap((error, count) => {
if (count >= 3) { // Maximum retry attempts
return throwError(error);
}
if (axios.isAxiosError(error) && error.response?.status === 502) { // Retry only on 502 Bad Gateway
return new Observable<AxiosResponse<any>>(observer => {
setTimeout(() => {
observer.next();
observer.complete();
}, 2000); // Wait 2 seconds before retrying
});
}
return throwError(error);
})
)
),
catchError(error => {
throw new BadGatewayException(error.message); // Throw custom exception if retries fail
})
);
}
}
Register the RetryInterceptor: Now, you need to register the RetryInterceptor
in your Nest.js module.
typescript// app.module.ts
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { RetryInterceptor } from './retry.interceptor';
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: RetryInterceptor,
},
],
})
export class AppModule {}
Use Axios for HTTP Requests: You can now use Axios for making HTTP requests within your Nest.js services or controllers. The interceptor will handle automatic retries for 502 Bad Gateway errors.
typescriptimport { Injectable } from '@nestjs/common';
import axios from 'axios';
@Injectable()
export class ApiService {
async fetchData(): Promise<any> {
try {
const response = await axios.get('https://example.com/api/data');
return response.data;
} catch (error) {
throw error; // Let Nest.js handle error responses
}
}
}
With this setup, Axios will automatically retry requests that fail due to a 502 Bad Gateway error, up to a maximum of three attempts. Adjust the conditions and retry logic in the interceptor according to your requirements.