Skip to content

Latest commit

 

History

History
297 lines (216 loc) · 6.68 KB

File metadata and controls

297 lines (216 loc) · 6.68 KB

@lenqwang/http-client

一个基于 Axios 的强大 HTTP 客户端库,提供请求重试、自动取消重复请求、拦截器管理等高级功能。

npm version TypeScript Test Coverage License

🌍 Multi-language Support: 中文 | English

✨ 特性

  • 🚀 基于 Axios: 继承 Axios 的所有功能和 API
  • 🔄 自动重试: 支持配置重试次数和延迟时间
  • 请求去重: 自动取消重复的请求
  • 🎯 拦截器管理: 灵活的请求和响应拦截器
  • 🛑 请求取消: 支持单个或批量取消请求
  • 📦 单例模式: 全局统一的 HTTP 客户端实例
  • 🔧 TypeScript: 完整的类型定义支持
  • 🧪 高测试覆盖率: 92.71% 的测试覆盖率

📦 安装

# npm
npm install @lenqwang/http-client

# yarn
yarn add @lenqwang/http-client

# pnpm
pnpm add @lenqwang/http-client

🚀 快速开始

基本使用

import httpClient from '@lenqwang/http-client';

// GET 请求
const response = await httpClient.get('/api/users');
console.log(response.data);

// POST 请求
const user = await httpClient.post('/api/users', {
  name: 'John Doe',
  email: 'john@example.com'
});

// PUT 请求
const updatedUser = await httpClient.put('/api/users/1', {
  name: 'Jane Doe'
});

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

🔧 高级功能

请求重试

// 配置重试参数
const response = await httpClient.request({
  url: '/api/data',
  method: 'GET',
  retryCount: 3,        // 重试 3 次
  retryDelay: 1000      // 每次重试延迟 1 秒
});

请求去重

// 相同的请求会自动取消前一个
const request1 = httpClient.get('/api/users');
const request2 = httpClient.get('/api/users'); // 会取消 request1

// 使用自定义请求键
const request3 = httpClient.get('/api/users', {
  requestKey: 'get-users-list'
});

手动取消请求

// 取消特定请求
const request = httpClient.get('/api/data', {
  requestKey: 'my-request'
});

httpClient.cancelRequest('my-request');

// 取消所有请求
httpClient.cancelAllRequests();

跳过响应拦截器

// 跳过默认的响应处理逻辑
const response = await httpClient.get('/api/raw-data', {
  skipResponseInterceptor: true
});

🎯 拦截器

添加请求拦截器

const requestInterceptorIds = httpClient.addRequestInterceptor({
  onFulfilled: (config) => {
    // 添加认证头
    config.headers.Authorization = `Bearer ${getToken()}`;
    return config;
  },
  onRejected: (error) => {
    console.error('Request error:', error);
    return Promise.reject(error);
  }
});

添加响应拦截器

const responseInterceptorIds = httpClient.addResponseInterceptor({
  onFulfilled: (response) => {
    // 处理响应数据
    if (response.data.code === 200) {
      return response;
    }
    throw new Error(response.data.message);
  },
  onRejected: (error) => {
    // 处理错误响应
    if (error.response?.status === 401) {
      // 重定向到登录页
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
});

移除拦截器

// 移除请求拦截器
httpClient.removeRequestInterceptor(...requestInterceptorIds);

// 移除响应拦截器
httpClient.removeResponseInterceptor(...responseInterceptorIds);

📋 API 参考

HttpClient 类

静态方法

  • getInstance(config?: CustomRequestConfig): HttpClientInstance
    • 获取 HttpClient 单例实例

实例方法

  • addRequestInterceptor(...interceptors: RequestInterceptor[]): number[]

    • 添加请求拦截器,返回拦截器 ID 数组
  • addResponseInterceptor(...interceptors: ResponseInterceptor[]): number[]

    • 添加响应拦截器,返回拦截器 ID 数组
  • removeRequestInterceptor(...interceptorIds: number[]): void

    • 移除指定的请求拦截器
  • removeResponseInterceptor(...interceptorIds: number[]): void

    • 移除指定的响应拦截器
  • cancelRequest(requestKey: string): void

    • 取消指定的请求
  • cancelAllRequests(): void

    • 取消所有进行中的请求
  • getRawAxios(): AxiosInstance

    • 获取原始的 Axios 实例

类型定义

CustomRequestConfig

interface CustomRequestConfig<D = any> extends AxiosRequestConfig<D> {
  skipResponseInterceptor?: boolean;  // 是否跳过响应拦截器
  retryCount?: number;                // 请求重试次数
  retryDelay?: number;                // 请求重试延迟(毫秒)
  requestKey?: string;                // 请求唯一标识
}

ResponseBody

interface ResponseBody<T = any> {
  code: number;     // 响应状态码
  data: T;          // 响应数据
  message: string;  // 响应消息
}

🔄 默认行为

请求拦截器

  • 自动为每个请求生成唯一的 requestKey(格式:${method}-${url}
  • 自动取消相同 requestKey 的重复请求
  • 为每个请求添加 AbortController 信号

响应拦截器

  • 检查响应数据的 code 字段,如果不等于 200 则抛出错误
  • 自动清理已完成请求的 requestKey
  • 支持跳过拦截器处理(skipResponseInterceptor: true

错误处理

  • 自动处理 Axios 取消错误
  • 支持请求重试机制
  • 重试时会递减 retryCount 并等待 retryDelay 时间

🧪 测试

# 运行测试
npm test

# 运行测试并生成覆盖率报告
npm run test:coverage

当前测试覆盖率:92.71%

🛠️ 开发

# 安装依赖
pnpm install

# 开发模式(监听文件变化)
npm run dev

# 构建
npm run build

# 发布
npm run release

📄 许可证

MIT License - 详见 LICENSE 文件

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📞 支持

如果您在使用过程中遇到问题,请:

  1. 查看 文档
  2. 搜索 Issues
  3. 提交新的 Issue

Made with ❤️ by LenqWang