Skip to content

lenqwang/http-client

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

11 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

@lenqwang/http-client

A powerful HTTP client library based on Axios, providing advanced features like request retry, automatic duplicate request cancellation, and interceptor management.

npm version TypeScript Test Coverage License

🌍 Multi-language Support: English | δΈ­ζ–‡

✨ Features

  • πŸš€ 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

πŸ“¦ Installation

# npm
npm install @lenqwang/http-client

# yarn
yarn add @lenqwang/http-client

# pnpm
pnpm add @lenqwang/http-client

πŸš€ Quick Start

Basic Usage

import 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');

Creating Custom Instance

import { HttpClient } from '@lenqwang/http-client';

const apiClient = HttpClient.getInstance({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  headers: {
    'Authorization': 'Bearer your-token'
  }
});

πŸ”§ Advanced Features

Request Retry

// 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
});

Request Deduplication

// 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'
});

Manual Request Cancellation

// Cancel specific request
const request = httpClient.get('/api/data', {
  requestKey: 'my-request'
});

httpClient.cancelRequest('my-request');

// Cancel all requests
httpClient.cancelAllRequests();

Skip Response Interceptor

// Skip default response handling logic
const response = await httpClient.get('/api/raw-data', {
  skipResponseInterceptor: true
});

🎯 Interceptors

Adding Request Interceptors

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);
  }
});

Adding Response Interceptors

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);
  }
});

Removing Interceptors

// Remove request interceptors
httpClient.removeRequestInterceptor(...requestInterceptorIds);

// Remove response interceptors
httpClient.removeResponseInterceptor(...responseInterceptorIds);

πŸ“‹ API Reference

HttpClient Class

Static Methods

  • getInstance(config?: CustomRequestConfig): HttpClientInstance
    • Get HttpClient singleton instance

Instance Methods

  • 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

Type Definitions

CustomRequestConfig

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
}

ResponseBody

interface ResponseBody<T = any> {
  code: number;     // Response status code
  data: T;          // Response data
  message: string;  // Response message
}

πŸ”„ Default Behavior

Request Interceptor

  • Automatically generates unique requestKey for each request (format: ${method}-${url})
  • Automatically cancels duplicate requests with the same requestKey
  • Adds AbortController signal to each request

Response Interceptor

  • Checks response data's code field, throws error if not equal to 200
  • Automatically cleans up completed request's requestKey
  • Supports skipping interceptor processing (skipResponseInterceptor: true)

Error Handling

  • Automatically handles Axios cancellation errors
  • Supports request retry mechanism
  • Decrements retryCount and waits for retryDelay time during retry

πŸ§ͺ Testing

# Run tests
npm test

# Run tests with coverage report
npm run test:coverage

Current test coverage: 92.71%

πŸ› οΈ Development

# Install dependencies
pnpm install

# Development mode (watch file changes)
npm run dev

# Build
npm run build

# Release
npm run release

πŸ“„ License

MIT License - see LICENSE file for details

🀝 Contributing

Issues and Pull Requests are welcome!

πŸ“ž Support

If you encounter any issues while using this library, please:

  1. Check the documentation
  2. Search Issues
  3. Submit a new Issue

Made with ❀️ by LenqWang

About

A powerful HTTP client library based on Axios, providing advanced features like request retry, automatic duplicate request cancellation, and interceptor management.

Resources

License

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors