AxiosService
is a utility class designed to encapsulate Axios HTTP requests with added features such as caching, request cancellation, token management, error handling, and performance monitoring. It aims to provide a robust and flexible HTTP service for modern JavaScript applications.
-
Initialization and Configuration
- Configures an Axios instance with default or custom settings including base URL, headers, timeout, caching, retry logic, and token management.
-
Global Error Handling
- Listens for unhandled promise rejections and general errors in the
window
context, logging errors to the console.
- Listens for unhandled promise rejections and general errors in the
-
Performance Monitoring
- Intercepts requests to log their start and end times, calculating request durations for performance monitoring.
-
Request Cancellation
- Intercepts requests to enable cancellation using Axios cancel tokens.
- Tracks ongoing requests to manage and cancel duplicate requests if required.
-
Token Management
- Manages authentication tokens, automatically refreshing expired tokens using a provided refresh token URL.
- Checks token expiration and refreshes tokens as needed to maintain API access.
-
HTTP Methods
- Provides wrapper methods for common Axios HTTP methods (
GET
,POST
,PUT
,DELETE
) with added functionalities such as caching responses and uniform error handling.
- Provides wrapper methods for common Axios HTTP methods (
-
Error Handling
- Centralized error handling for Axios requests, including automatic retry on token refresh (
401 Unauthorized
error).
- Centralized error handling for Axios requests, including automatic retry on token refresh (
-
Instance Creation
- Static method
createInstance()
allows creating instances ofAxiosService
with custom configurations.
- Static method
import AxiosService from './AxiosService';
// Create an instance of AxiosService with custom configurations
const axiosInstance = AxiosService.createInstance({
baseURL: 'https://api.example.com',
headers: {
'X-Custom-Header': 'foobar',
},
cacheEnabled: true,
retry: true,
tokenRefreshEnabled: true,
});
// Example GET request
axiosInstance.get('/data', { params: { key: 'value' } })
.then(data => {
console.log('Response:', data);
})
.catch(error => {
console.error('Request failed:', error);
});
- Initializes the
AxiosService
instance with default and custom configuration options. - Configures Axios instance, caching, retry logic, token management, and other features based on provided settings.
- Attempts to refresh the authentication token using a specified refresh token URL.
- Updates
token
andtokenExpiration
upon successful token refresh.
- Retrieves the current authentication token.
- Refreshes the token if expired or not available.
- Checks if the current authentication token is expired.
- Performs a GET request to the specified URL with optional parameters and configuration.
- Implements caching of responses if enabled.
- Performs a POST request to the specified URL with data and optional configuration.
- Performs a PUT request to the specified URL with data and optional configuration.
- Performs a DELETE request to the specified URL with optional configuration.
- Handles successful HTTP responses, extracting and returning response data.
- Centralized error handling for Axios requests.
- Automatically retries requests upon token refresh if
401 Unauthorized
error occurs. - Logs specific error details including status codes and response data.
- Creates a new instance of
AxiosService
with custom configuration options. - Returns the initialized instance ready for HTTP requests.
- Handles various HTTP errors including
401 Unauthorized
for automatic token refresh. - Logs detailed error information for debugging and monitoring purposes.
- Secure handling of authentication tokens and sensitive data such as refresh tokens.
- Usage of secure storage or environment variables for sensitive configurations.
- Logs request durations to monitor API performance and response times.
- Supports cancellation of ongoing requests to prevent redundant API calls.
- Manages Axios cancel tokens to handle request cancellation efficiently.
- Requires
axios
for HTTP requests andnode-cache
for caching (optional).
- Building robust API clients for frontend applications.
- Integrating with RESTful APIs that require token-based authentication.
- Managing and monitoring API performance and error handling in JavaScript applications.