npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@via-cli/axios-helper

v0.0.2

Published

企业级的axios工具二次封装、包含接口数据缓存、合并相同请求、失败重试等业务功能

Downloads

9

Readme

@via-cli/axios-helper

企业级 Axios 封装库,提供智能缓存、请求合并、自动重试、Go风格错误处理等功能。

特性

  • 🚀 智能缓存 - 基于 @via-cli/cache-tools 的高效缓存机制
  • 🔄 请求合并 - 自动合并相同的并发请求,避免重复调用
  • 🔁 自动重试 - 可配置的重试策略,提高请求成功率
  • 🛡️ Go风格错误处理 - [error, data] 元组返回,简化错误处理
  • 🔐 灵活认证 - 支持函数式token和header配置
  • 📝 完整类型支持 - 全面的 TypeScript 类型定义
  • 高性能 - 优化的请求处理和内存管理
  • 🔧 易于配置 - 支持全局和请求级别的灵活配置

📦 安装

# 使用 pnpm (推荐)
pnpm add @via-cli/axios-helper

# 使用 npm
npm install @via-cli/axios-helper

# 使用 yarn
yarn add @via-cli/axios-helper

依赖要求

  • axios: ^1.6.0
  • @via-cli/cache-tools: ^1.0.0 (用于缓存功能)

🚀 快速开始

基础用法

import { AxiosHelper } from '@via-cli/axios-helper'

// 全局配置
AxiosHelper.configure({
  baseURL: 'https://api.example.com',
  timeout: 10000
})

// 发送请求
const [error, users] = await AxiosHelper.get<User[]>('/users')
if (error) {
  console.error('请求失败:', error.message)
} else {
  console.log('用户列表:', users)
}

带认证的请求

// 配置认证
AxiosHelper.configure({
  baseURL: 'https://api.example.com',
  token: () => localStorage.getItem('auth-token'),
  headers: (config) => {
    config.headers['X-App-Version'] = '1.0.0'
    config.headers['X-Platform'] = 'web'
    return config
  }
})

// 需要认证的请求
const [error, profile] = await AxiosHelper.get<UserProfile>('/profile', {
  needAuth: true
})

带缓存的请求

const [error, user] = await AxiosHelper.get<User>('/users/123', {
  cache: {
    enabled: true,
    expire: 300, // 5分钟缓存
    namespace: 'users',
    key: 'user-123'
  }
})

带重试的请求

const [error, data] = await AxiosHelper.get('/api/critical-data', {
  retry: {
    enabled: true,
    times: 3,
    delay: 1000,
    condition: (error) => {
      // 只对服务器错误重试
      return !error.response || error.response.status >= 500
    }
  }
})

📖 API 文档

配置方法

AxiosHelper.configure(config)

设置全局配置,支持以下选项:

interface AxiosHelperConfig {
  baseURL?: string
  timeout?: number
  token?: () => string | null
  headers?: (config: any) => any
  mergeRequest?: {
    enabled: boolean
    mergeWindow: number
  }
  onError?: (error: AxiosError) => void
}

AxiosHelper.getConfig()

获取当前配置的副本。

HTTP 请求方法

AxiosHelper.get<T>(url, options)

发送 GET 请求,返回 Promise<[AxiosError | null, T | null]>

AxiosHelper.post<T>(url, data, options)

发送 POST 请求,返回 Promise<[AxiosError | null, T | null]>

AxiosHelper.put<T>(url, data, options)

发送 PUT 请求,返回 Promise<[AxiosError | null, T | null]>

AxiosHelper.del<T>(url, options)

发送 DELETE 请求,返回 Promise<[AxiosError | null, T | null]>

请求选项

interface RequestOptions {
  cache?: {
    enabled: boolean
    expire?: number
    namespace?: string
    key?: string
  }
  retry?: {
    enabled: boolean
    times?: number
    delay?: number
    condition?: (error: AxiosError) => boolean
  }
  needAuth?: boolean
  headers?: Record<string, string>
  timeout?: number
}

缓存管理

AxiosHelper.clearCache(pattern?, namespace?)

清理缓存数据。

AxiosHelper.getCacheStats()

获取缓存统计信息。

使用场景

用户管理服务

import { AxiosHelper } from '@via-cli/axios-helper'

export class UserService {
  // 获取用户列表(带缓存)
  static async getUsers() {
    const [error, users] = await AxiosHelper.get<User[]>('/users', {
      cache: {
        enabled: true,
        expire: 300,
        namespace: 'users',
        key: 'user-list'
      },
      needAuth: true
    })
    return { error, users }
  }

  // 创建用户
  static async createUser(userData: Omit<User, 'id'>) {
    const [error, newUser] = await AxiosHelper.post<User>('/users', userData, {
      needAuth: true,
      retry: {
        enabled: true,
        times: 2,
        delay: 1000
      }
    })

    if (!error) {
      // 清理相关缓存
      AxiosHelper.clearCache(undefined, 'users')
    }

    return { error, user: newUser }
  }
}

文件上传

export class UploadService {
  static async uploadFile(file: File) {
    const formData = new FormData()
    formData.append('file', file)

    const [error, result] = await AxiosHelper.post<{ url: string }>('/upload', formData, {
      needAuth: true,
      headers: { 'Content-Type': 'multipart/form-data' },
      timeout: 60000,
      retry: { enabled: false }
    })

    return { error, result }
  }
}

错误处理最佳实践

import type { AxiosError } from '@via-cli/axios-helper'

export class ErrorHandler {
  static handle(error: AxiosError | null, context?: string) {
    if (!error) return

    switch (error.status) {
      case 401:
        console.error('认证失败')
        // 跳转到登录页
        break
      case 403:
        console.error('权限不足')
        break
      case 404:
        console.error('资源不存在')
        break
      default:
        console.error('请求失败:', error.message)
    }
  }
}

性能优化建议

  1. 合理使用缓存 - 静态数据使用长缓存,动态数据使用短缓存
  2. 启用请求合并 - 减少相同的并发请求
  3. 定期清理缓存 - 避免内存泄漏
  4. 监控缓存性能 - 使用 getCacheStats() 监控命中率

🤝 贡献

欢迎提交 Issue 和 Pull Request 来帮助改进这个项目。

📄 许可证

MIT © 朝阳前端团队