To use the Node.js Axios library for making HTTP requests with interceptors for retries and timeouts in Nest.js, you can follow these steps:
bashnpm install axios
typescript// axios.service.ts
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { Injectable } from '@nestjs/common';
@Injectable()
export class AxiosService {
private readonly axiosInstance: AxiosInstance;
constructor() {
this.axiosInstance = axios.create({
// Axios configuration options
timeout: 5000, // Default request timeout in milliseconds
});
// Add interceptors
this.setupInterceptors();
}
private setupInterceptors() {
// Add a request interceptor for retries
this.axiosInstance.interceptors.request.use(
(config: AxiosRequestConfig) => {
// Your retry logic here
return config;
},
(error) => {
return Promise.reject(error);
},
);
// Add a response interceptor for retries
this.axiosInstance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
// Your retry logic here
return Promise.reject(error);
},
);
}
// Method to make HTTP requests
async makeRequest(config: AxiosRequestConfig) {
try {
const response = await this.axiosInstance.request(config);
return response.data;
} catch (error) {
throw error.response.data || error.message;
}
}
}
typescript// your.module.ts
import { Module } from '@nestjs/common';
import { AxiosService } from './axios.service';
@Module({
providers: [AxiosService],
exports: [AxiosService],
})
export class YourModule {}
typescript// your.controller.ts
import { Controller, Get } from '@nestjs/common';
import { AxiosService } from './axios.service';
@Controller('example')
export class YourController {
constructor(private readonly axiosService: AxiosService) {}
@Get()
async getExampleData() {
try {
const data = await this.axiosService.makeRequest({
method: 'get',
url: 'https://api.example.com/data',
});
return data;
} catch (error) {
throw new Error(`Failed to fetch data: ${error.message}`);
}
}
}
Customize Axios Configuration: You can customize the Axios instance configuration options (e.g., timeouts, base URL) in the AxiosService
constructor according to your requirements.
Implement Retry Logic: Within the request and response interceptors, you can implement retry logic based on the error conditions.
By following these steps, you can integrate Axios with interceptors for retries and timeouts into your Nest.js application. Adjust the interceptor logic according to your specific requirements.