A powerful HTTP client library based on Axios, providing advanced features like request retry, automatic duplicate request cancellation, and interceptor management.
π Multi-language Support: English | δΈζ
- π Based on Axios: Inherits all Axios functionality and APIs
- π Automatic Retry: Configurable retry count and delay
- β‘ Request Deduplication: Automatically cancels duplicate requests
- π― Interceptor Management: Flexible request and response interceptors
- π Request Cancellation: Support for individual or batch request cancellation
- π¦ Singleton Pattern: Global unified HTTP client instance
- π§ TypeScript: Complete type definition support
- π§ͺ High Test Coverage: 92.71% test coverage
# npm
npm install @lenqwang/http-client
# yarn
yarn add @lenqwang/http-client
# pnpm
pnpm add @lenqwang/http-clientimport httpClient from '@lenqwang/http-client';
// GET request
const response = await httpClient.get('/api/users');
console.log(response.data);
// POST request
const user = await httpClient.post('/api/users', {
name: 'John Doe',
email: 'john@example.com'
});
// PUT request
const updatedUser = await httpClient.put('/api/users/1', {
name: 'Jane Doe'
});
// DELETE request
await httpClient.delete('/api/users/1');import { HttpClient } from '@lenqwang/http-client';
const apiClient = HttpClient.getInstance({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'Authorization': 'Bearer your-token'
}
});// Configure retry parameters
const response = await httpClient.request({
url: '/api/data',
method: 'GET',
retryCount: 3, // Retry 3 times
retryDelay: 1000 // 1 second delay between retries
});// Identical requests will automatically cancel the previous one
const request1 = httpClient.get('/api/users');
const request2 = httpClient.get('/api/users'); // Will cancel request1
// Using custom request key
const request3 = httpClient.get('/api/users', {
requestKey: 'get-users-list'
});// Cancel specific request
const request = httpClient.get('/api/data', {
requestKey: 'my-request'
});
httpClient.cancelRequest('my-request');
// Cancel all requests
httpClient.cancelAllRequests();// Skip default response handling logic
const response = await httpClient.get('/api/raw-data', {
skipResponseInterceptor: true
});const requestInterceptorIds = httpClient.addRequestInterceptor({
onFulfilled: (config) => {
// Add authentication header
config.headers.Authorization = `Bearer ${getToken()}`;
return config;
},
onRejected: (error) => {
console.error('Request error:', error);
return Promise.reject(error);
}
});const responseInterceptorIds = httpClient.addResponseInterceptor({
onFulfilled: (response) => {
// Handle response data
if (response.data.code === 200) {
return response;
}
throw new Error(response.data.message);
},
onRejected: (error) => {
// Handle error response
if (error.response?.status === 401) {
// Redirect to login page
window.location.href = '/login';
}
return Promise.reject(error);
}
});// Remove request interceptors
httpClient.removeRequestInterceptor(...requestInterceptorIds);
// Remove response interceptors
httpClient.removeResponseInterceptor(...responseInterceptorIds);getInstance(config?: CustomRequestConfig): HttpClientInstance- Get HttpClient singleton instance
-
addRequestInterceptor(...interceptors: RequestInterceptor[]): number[]- Add request interceptors, returns array of interceptor IDs
-
addResponseInterceptor(...interceptors: ResponseInterceptor[]): number[]- Add response interceptors, returns array of interceptor IDs
-
removeRequestInterceptor(...interceptorIds: number[]): void- Remove specified request interceptors
-
removeResponseInterceptor(...interceptorIds: number[]): void- Remove specified response interceptors
-
cancelRequest(requestKey: string): void- Cancel specified request
-
cancelAllRequests(): void- Cancel all ongoing requests
-
getRawAxios(): AxiosInstance- Get raw Axios instance
interface CustomRequestConfig<D = any> extends AxiosRequestConfig<D> {
skipResponseInterceptor?: boolean; // Whether to skip response interceptor
retryCount?: number; // Request retry count
retryDelay?: number; // Request retry delay (milliseconds)
requestKey?: string; // Request unique identifier
}interface ResponseBody<T = any> {
code: number; // Response status code
data: T; // Response data
message: string; // Response message
}- Automatically generates unique
requestKeyfor each request (format:${method}-${url}) - Automatically cancels duplicate requests with the same
requestKey - Adds
AbortControllersignal to each request
- Checks response data's
codefield, throws error if not equal to 200 - Automatically cleans up completed request's
requestKey - Supports skipping interceptor processing (
skipResponseInterceptor: true)
- Automatically handles Axios cancellation errors
- Supports request retry mechanism
- Decrements
retryCountand waits forretryDelaytime during retry
# Run tests
npm test
# Run tests with coverage report
npm run test:coverageCurrent test coverage: 92.71%
# Install dependencies
pnpm install
# Development mode (watch file changes)
npm run dev
# Build
npm run build
# Release
npm run releaseMIT License - see LICENSE file for details
Issues and Pull Requests are welcome!
If you encounter any issues while using this library, please:
- Check the documentation
- Search Issues
- Submit a new Issue
Made with β€οΈ by LenqWang