To use Axios with interceptors for automatic timeout handling in a Nest.js application, you can create a custom interceptor to handle timeouts. Here's how you can achieve this:
Install Axios:
First, ensure 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 TimeoutInterceptor:
In Nest.js, interceptors are used to intercept and manipulate requests and responses. You can create a custom interceptor to handle timeouts.
typescript// timeout.interceptor.ts
import { Injectable, NestInterceptor, ExecutionContext, CallHandler, HttpException, HttpStatus } from '@nestjs/common';
import { Observable, throwError, TimeoutError } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';
import axios, { AxiosRequestConfig } from 'axios';
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const request = context.switchToHttp().getRequest();
const timeoutValue = request.timeout || 5000; // Default timeout is 5 seconds
return next.handle().pipe(
timeout(timeoutValue),
catchError(error => {
if (error instanceof TimeoutError) {
throw new HttpException('Request timed out', HttpStatus.REQUEST_TIMEOUT);
} else {
return throwError(error);
}
})
);
}
}
In this interceptor, we're setting a default timeout value of 5 seconds (5000 milliseconds). You can adjust this value according to your requirements. Additionally, if the timeout is reached, the interceptor throws an HTTP exception with status code 408 (Request Timeout).
Register the TimeoutInterceptor:
Register the TimeoutInterceptor
in your Nest.js module to apply it to HTTP requests.
typescript// app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { TimeoutInterceptor } from './timeout.interceptor';
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: TimeoutInterceptor,
},
],
})
export class AppModule {}
Use Axios for HTTP Requests:
Now, you can use Axios for making HTTP requests within your Nest.js services or controllers. The interceptor will handle timeouts automatically.
typescriptimport { Injectable } from '@nestjs/common';
import axios from 'axios';
@Injectable()
export class ApiService {
async fetchData(): Promise<any> {
try {
const response = await axios.get('https://api.example.com/data', { timeout: 10000 }); // Set custom timeout if needed
return response.data;
} catch (error) {
throw error; // Let Nest.js handle error responses
}
}
}
In this example, we're setting a custom timeout value of 10 seconds (10000 milliseconds) for the specific request. This overrides the default timeout value set in the interceptor.
With this setup, Axios will automatically handle timeouts for HTTP requests in your Nest.js application. Adjust the interceptor's timeout value and the custom timeout values in individual requests according to your specific requirements.