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

@zym-test-zerog/api-client-sdk

v0.1.0

Published

Api 平台接口

Readme

Api 平台接口 TypeScript SDK 技术方案

1. 项目概述

本项目是一个基于 TypeScript、Axios 和 Crypto-JS 构建的 Api 平台接口 SDK,使用 TSUP 作为构建工具,提供了一套完整的客户端解决方案,包括 API 请求处理、签名机制、Token 管理、日志记录和错误处理等功能。SDK 支持 CommonJS 和 ES Module 两种模块格式,可在浏览器和 Node.js 环境中使用。

2. 功能介绍

2.1 核心功能

| 功能模块 | 描述 | |---------|------| | API 请求处理 | 封装了 Axios 库,提供统一的请求接口 | | 签名机制 | 自动生成请求签名,确保接口安全性 | | Token 管理 | 支持 Token 存储、获取和自动刷新 | | 日志记录 | 提供多级别的日志记录功能,支持自定义日志输出 | | 错误处理 | 统一的错误类型定义和错误回调机制 | | 业务错误映射 | 支持业务错误码到错误信息的映射 |

2.2 扩展功能

  • 调试模式:支持开启/关闭调试日志
  • 日志级别控制:支持 all、error、info 三个级别的日志控制
  • 自定义日志回调:支持将日志输出到外部系统
  • 统一错误回调:支持全局错误监听和上报

3. 技术选型与分析

3.1 核心技术栈

| 技术/库 | 版本 | 用途 | 选型理由 | |--------|------|------|---------| | TypeScript | 5.4.5 | 开发语言 | 提供类型安全,增强代码可维护性和可读性 | | Axios | 1.6.7 | HTTP 客户端 | 成熟稳定,支持浏览器和 Node.js 环境,提供丰富的拦截器功能 | | Crypto-JS | 4.2.0 | 加密库 | 用于生成请求签名,支持 MD5 等多种加密算法 | | ESLint | 9.3.0 | 代码质量检查 | 提供强大的代码质量检查能力,支持自定义规则,社区生态丰富 | | TypeScript ESLint | 8.0.0 | TypeScript 代码检查规则 | 专为 TypeScript 设计,与 ESLint 无缝集成,提供针对 TypeScript 语法的专业检查规则 | | tsup | 8.0.2 | 构建工具 | 基于 ESBuild,构建速度极快,配置简单,原生支持 TypeScript 和多格式输出 |

3.2 构建工具选型

选择 TSUP 而非 Rollup 的原因分析: | 维度 | TSUP | Rollup | |------|------|--------| | 配置复杂度 | 极简配置,开箱即用 | 需要手动配置插件链(如 @rollup/plugin-typescript、@rollup/plugin-commonjs 等) | | 构建速度 | 基于 ESBuild,构建速度极快 | 构建速度较慢,尤其是在大型项目中 | | TypeScript 支持 | 原生支持 TypeScript,无需额外配置 | 需要配置 @rollup/plugin-typescript 或 esbuild 插件 | | 多格式输出 | 内置支持 CJS、ESM 等多种格式 | 需要配置 output.format 数组 | | Source Map 支持 | 内置支持,配置简单 | 需要配置 sourcemap 选项 | | 类型声明生成 | 内置支持生成 .d.ts 文件 | 需要配置 @rollup/plugin-typescript 或 tsc 命令 | | 零配置体验 | 支持零配置启动 | 需要编写完整配置文件 | | 社区生态 | 专注于 TypeScript 项目,社区活跃 | 生态丰富,但配置复杂 | 结论:TSUP 更适合 TypeScript 库的快速开发和构建,提供了极简的配置体验和极快的构建速度,同时支持所有必要的功能,如多格式输出、Source Map 生成和类型声明生成。

4. 架构设计

4.1 整体架构

4.1.1 目录结构

src/
├── api/                  # API 接口层 - 业务接口封装
│   └── v1/               # API 版本 v1
│       ├── airline.ts    # 航线相关接口
│       ├── auth.ts       # 认证相关接口
│       ├── fence.ts      # 围栏相关接口
│       └── index.ts      # API 入口文件,导出所有 v1 接口
├── client/               # 客户端核心层 - 基础功能实现
│   ├── http.ts           # HTTP 请求处理,包含拦截器、请求/响应处理
│   ├── log-storage.ts    # 日志存储管理,负责日志的持久化和查询
│   ├── logger.ts         # 日志记录功能,支持多级别日志
│   ├── sign.ts           # 签名生成与验证
│   ├── state.ts          # 状态管理,存储配置、日志等
│   └── token.ts          # Token 存储与管理
├── types/                # 类型定义层 - TypeScript 类型定义
│   └── v1/               # API 版本 v1 类型定义
│       ├── airline.ts    # 航线相关类型
│       ├── auth.ts       # 认证相关类型
│       ├── fence.ts      # 围栏相关类型
│       └── index.ts      # 类型入口文件,导出所有 v1 类型
├── index.ts              # SDK 主入口,导出所有公开 API
└── types.ts              # 核心类型定义,包含 SDK 配置、错误类型等

4.1.2 核心工作流程

  1. 初始化流程
    • 应用程序调用 initApiClient() 初始化 SDK
    • 配置信息存储到状态管理中
    • 创建 HTTP 客户端实例
    • 设置请求/响应拦截器
  2. API 调用流程
    • 应用程序调用 SDK 导出的 API 方法
    • API 方法内部调用 requestData() 函数
    • requestData() 获取 HTTP 客户端实例
    • 执行请求,经过请求拦截器处理(签名生成、Token 注入)
    • 发送 HTTP 请求到服务器
    • 响应返回后,经过响应拦截器处理(日志记录、错误处理、Token 刷新)
    • 返回处理后的数据或抛出错误
  3. Token 刷新流程
    • 当检测到 401 错误时,自动触发 Token 刷新
    • 调用 /auth/v1/refresh 接口获取新 Token
    • 更新 Token 存储
    • 重新执行之前失败的请求
  4. 签名生成流程
    • 收集请求参数(URI、时间戳、nonce、查询参数、请求体)
    • 过滤和排序参数
    • 拼接签名字符串
    • 使用 MD5 算法加盐加密生成签名
    • 将签名添加到请求头中

4.2 核心流程

4.2.1 API 请求流程

sequenceDiagram
    participant App as 应用程序
    participant API as API 方法
    participant Request as requestData 函数
    participant Client as HTTP 客户端
    participant Interceptor as 请求拦截器
    participant Server as 服务器
    participant ResponseInterceptor as 响应拦截器
    
    App->>API: 调用 API 方法
    API->>Request: 调用 requestData
    Request->>Client: 获取 HTTP 客户端实例
    Client->>Interceptor: 执行请求
    
    Note over Interceptor: 请求拦截器处理流程
    Interceptor->>Interceptor: 1. 生成时间戳和随机 nonce
    Interceptor->>Interceptor: 2. 设置 Token 到请求头
    Interceptor->>Interceptor: 3. 生成请求签名并设置到请求头
    
    Interceptor->>Server: 发送 HTTP 请求
    Server-->>ResponseInterceptor: 返回响应
    
    Note over ResponseInterceptor: 响应拦截器处理流程
    ResponseInterceptor->>ResponseInterceptor: 1. 记录请求日志
    ResponseInterceptor->>ResponseInterceptor: 2. 检查业务状态码
    
    alt 业务状态码正常
        ResponseInterceptor-->>Request: 返回响应数据
        Request-->>API: 返回数据
        API-->>App: 返回数据
    else 业务状态码错误
        ResponseInterceptor->>ResponseInterceptor: 3. 生成 ApiError 并抛出
        ResponseInterceptor-->>Request: 抛出错误
        Request-->>API: 抛出错误
        API-->>App: 抛出错误
    end
    
    alt 401 错误 (Token 过期)
        ResponseInterceptor->>ResponseInterceptor: 2. Token 自动刷新
        ResponseInterceptor-->>Request: 重新执行请求
    else 其他 HTTP 错误
        ResponseInterceptor->>ResponseInterceptor: 3. 生成 ApiError 并抛出
        ResponseInterceptor-->>Request: 抛出错误
        Request-->>API: 抛出错误
        API-->>App: 抛出错误
    end

4.2.2 Token 刷新流程

flowchart TD
    A[检测到 401 错误] --> B{是否正在刷新 Token?}
    
    B -->|是| C[将当前请求加入 pending 队列]
    C --> D[等待刷新完成]
    
    B -->|否| E[设置 isRefreshing = true]
    E --> F[调用 /auth/v1/refresh 接口]
    
    F --> G{刷新成功?}
    
    G -->|是| H[更新 Token 存储]
    H --> I[记录 Token 刷新日志]
    I --> J[处理 pending 队列中的请求]
    J --> K[设置 isRefreshing = false]
    K --> L[清空 refreshPromise]
    L --> M[返回新 Token]
    
    G -->|否| N[处理 pending 队列中的请求]
    N --> K
    L --> O[抛出错误]
    
    D --> M
    
    classDef process fill:#cdf,stroke:#333,stroke-width:1px;
    classDef decision fill:#ff9,stroke:#333,stroke-width:1px;
    classDef action fill:#bbf,stroke:#333,stroke-width:1px;
    
    class A,C,D,E,F,H,I,J,K,L,M,N,O process;
    class B,G decision;

5. 核心模块设计与实现

5.1 HTTP 客户端模块 (client/http.ts)

5.1.1 主要功能

  • 创建和配置 Axios 实例
  • 请求拦截器:添加签名、Token 等
  • 响应拦截器:处理业务错误、Token 刷新等
  • 提供统一的请求方法

5.1.2 核心代码结构

// 创建 HTTP 客户端
export function createHttpClient(config: ApiClientConfig): AxiosInstance
// 初始化 Api 客户端
export function initApiClient(config: ApiClientConfig): void
// 获取 HTTP 客户端实例
export function getHttpClient(): AxiosInstance
// 请求数据
export async function requestData<TData>(
  cfg: AxiosRequestConfig,
  apiName?: string
): Promise<TData>
// 刷新 Token
async function refreshToken(instance: AxiosInstance, config: ApiClientConfig): Promise<string>

5.2 签名模块 (client/sign.ts)

5.2.1 签名算法

  1. 参数收集:收集 URI、时间戳、nonce、查询参数和请求体
  2. 参数过滤:移除 null、undefined 和空字符串值
  3. 参数排序:按参数名字母顺序排序
  4. 序列化:将参数值序列化为字符串
  5. 拼接签名字符串:格式为 key1=value1&key2=value2&secret=secret
  6. 加密:使用 MD5 算法,加盐加密

5.2.2 核心代码

export function generateSign(input: SignInput): { sign: string; signString: string }
export function randomNonce(): string

5.3 Token 管理模块 (client/token.ts)

5.3.1 主要功能

  • Token 的存储和获取
  • 支持 Token 自动刷新

5.3.2 核心代码

export function setApiToken(token: string | undefined): void
export function getApiToken(): string | undefined

5.4 日志模块 (client/logger.ts)

5.4.1 主要功能

  • 日志级别控制
  • 日志格式化
  • 日志输出(控制台和自定义回调)
  • HTTP日志彩色打印

5.4.2 核心代码

export function handleHttpLog(
  config: ApiClientConfig,
  level: Exclude<ApiLogLevel, 'all'>,
  log: ApiStructuredHttpLog
): void
export function emitLog(
  config: ApiClientConfig | undefined,
  level: Exclude<ApiLogLevel, 'all'>,
  line: string,
  meta?: unknown
): void

5.5 日志存储模块 (client/log-storage.ts)

5.5.1 主要功能

  • 日志的持久化存储
  • 日志查询和过滤
  • 日志清理和管理

5.5.2 核心代码

export function getLogs(): string[]
export function getErrors(): { timestamp: number; error: ApiError }[]
export function clearLogs(): void
export function clearErrors(): void
export function clearAllLogs(): void

5.6 状态管理模块 (client/state.ts)

5.6.1 主要功能

  • 存储 SDK 配置
  • 存储 Axios 实例
  • 存储 Token
  • 存储日志和错误信息

5.6.2 核心代码

export interface ApiClientState {
  config?: ApiClientConfig;
  axios?: AxiosInstance;
  token?: string;
  logs: ApiLogEntry[];
  errors: ApiErrorLogEntry[];
}
export const state: ApiClientState = {
  logs: [],
  errors: []
};

6. 类型定义

6.1 核心类型

6.1.1 ApiClientConfig

export interface ApiClientConfig {
  baseUrl: string;           // API 基础 URL
  secret: string;            // 密钥
  salt: string;              // 加密盐值
  debug?: boolean;           // 是否开启调试模式
  logLevel?: ApiLogLevel;     // 日志等级
  logger?: (line: string, level: Exclude<ApiLogLevel, 'all'>, meta?: unknown) => void;  // 自定义日志输出
  onError?: (error: ApiError) => void;  // 统一错误回调
  businessErrorMessageMap?: Record<number, string>;  // 业务错误码映射
}

6.1.2 ApiApiResponse

export interface ApiApiResponse<T> {
  code: number;              // 响应状态码
  msg?: string;              // 响应消息(短)
  message?: string;          // 响应消息(长)
  sub_code?: number;         // 子错误码
  sub_msg?: string;          // 子错误消息
  data?: T;                  // 响应数据
}

6.1.3 ApiError

export class ApiError extends Error {
  public readonly type: ApiErrorType;       // 错误类型
  public readonly httpStatus?: number;     // HTTP 状态码
  public readonly code?: number;           // 业务错误码
  public readonly subCode?: number;        // 业务子错误码
  public readonly subMsg?: string;         // 业务子错误消息
  public readonly raw?: unknown;           // 原始错误数据
}

6.1.4 ApiLogEntry

export interface ApiLogEntry {
  timestamp: number;                      // 时间戳
  level: Exclude<ApiLogLevel, 'all'>;     // 日志等级
  message: string;                        // 日志内容
  meta?: unknown;                         // 元数据
}

6.1.5 ApiErrorLogEntry

export interface ApiErrorLogEntry {
  timestamp: number;                      // 时间戳
  error: ApiError;                        // 错误对象
}

6.1.6 ApiStructuredHttpLog

export interface ApiStructuredHttpLog {
  name?: string;                          // API名称
  url?: string;                           // 请求URL
  method?: string;                        // 请求方法
  headers?: unknown;                      // 请求头
  request?: unknown;                      // 请求体
  response?: unknown;                     // 响应体
  durationMs?: number;                    // 请求时长(毫秒)
  status?: number;                        // HTTP状态码
}

6.2 错误类型

export type ApiErrorType = 'network' | 'server' | 'auth' | 'business' | 'unknown';

6.3 日志级别

export type ApiLogLevel = 'all' | 'info' | 'error';

7. API 设计

7.1 初始化 API

export function initApiClient(config: ApiClientConfig): void

7.2 Token 管理 API

export function setApiToken(token: string | undefined): void
export function getApiToken(): string | undefined

7.3 日志管理 API

export function getLogs(): string[]
export function getErrors(): { timestamp: number; error: ApiError }[]
export function clearLogs(): void
export function clearErrors(): void
export function clearAllLogs(): void

7.4 业务 API

7.4.1 认证相关 API

export function loginApi(params: LoginParams): Promise<LoginResponse>
export function refreshTokenApi(): Promise<RefreshTokenResponse>
export function logoutApi(): Promise<LogoutResponse>

7.4.2 航线相关 API

export function airlineAddApi(params: AirlineAddParams): Promise<AirlineAddResponse>
export function airlineListApi(params: AirlineListParams): Promise<AirlineListResponse>
export function airlineQueryApi(params: AirlineQueryParams): Promise<AirlineQueryResponse>
export function airlineUpdateApi(params: AirlineUpdateParams): Promise<AirlineUpdateResponse>

7.4.3 围栏相关 API

export function fenceAddApi(params: FenceAddParams): Promise<FenceAddResponse>
export function fenceListApi(params: FenceListParams): Promise<FenceListResponse>
export function fenceQueryApi(params: FenceQueryParams): Promise<FenceQueryResponse>
export function fenceUpdateApi(params: FenceUpdateParams): Promise<FenceUpdateResponse>

8. 使用方法

8.1 安装

npm install api-client-sdk

8.2 初始化

import { initApiClient, setApiToken } from 'api-client-sdk';
// 初始化 SDK
initApiClient({
  baseUrl: 'https://api.example.com',
  secret: 'your-secret',
  salt: 'your-salt',
  debug: true,
  logLevel: 'info',
  onError: (error) => {
    // 自定义错误处理
    console.error('Api SDK Error:', error);
  },
  businessErrorMessageMap: {
    1001: '用户名或密码错误',
    1002: '验证码过期'
  }
});
// 设置初始 Token
setApiToken('initial-token');

8.3 调用 API

import { loginApi, airlineListApi } from 'api-client-sdk';
// 登录
try {
  const loginResult = await loginApi({
    username: 'admin',
    password: 'password'
  });
  console.log('Login success:', loginResult);
} catch (error) {
  console.error('Login failed:', error);
}
// 获取航线列表
try {
  const airlines = await airlineListApi({
    page: 1,
    pageSize: 10
  });
  console.log('Airlines:', airlines);
} catch (error) {
  console.error('Failed to get airlines:', error);
}

8.4 日志管理

import { getLogs, getErrors, clearAllLogs } from 'api-client-sdk';
// 获取日志
const logs = getLogs();
console.log('Logs:', logs);
// 获取错误
const errors = getErrors();
console.log('Errors:', errors);
// 清除所有日志
clearAllLogs();

9. 优势与特点

9.1 易用性

  • 简单的 API 设计:提供简洁明了的 API 接口,易于集成和使用
  • 自动处理:自动处理签名生成、Token 刷新、错误处理等复杂逻辑
  • 完整的类型定义:提供全面的 TypeScript 类型定义,支持 IDE 智能提示

9.2 安全性

  • 请求签名机制:确保 API 请求的完整性和安全性
  • Token 管理:支持 Token 自动刷新,减少安全风险
  • 加密传输:依赖 HTTPS 协议,确保数据传输安全

9.3 可维护性

  • 模块化设计:代码结构清晰,模块化程度高,易于维护和扩展
  • 完整的日志记录:提供详细的日志记录,便于调试和问题定位
  • 统一的错误处理:集中处理各种错误类型,便于监控和上报

9.4 性能

  • 高效的构建工具:使用 TSUP 构建,构建速度极快
  • 优化的请求处理:减少不必要的请求,提高请求效率
  • 合理的缓存策略:避免重复请求,提高性能

10. 可行性评估

10.1 技术可行性

  • 成熟的技术栈:使用 TypeScript、Axios 等成熟技术,技术风险低
  • 完整的功能实现:覆盖了 API 请求处理、签名机制、Token 管理、日志记录和错误处理等核心功能
  • 良好的扩展性:模块化设计,便于扩展新的功能和业务模块

10.2 兼容性

  • 支持多种模块格式:同时支持 CommonJS 和 ES Module
  • 跨环境支持:可在浏览器和 Node.js 环境中使用
  • 依赖精简:仅依赖 Axios 和 Crypto-JS 两个核心库,依赖冲突风险低

10.3 性能评估

  • 构建速度:使用 TSUP 构建,构建时间短
  • 运行时性能:核心逻辑简洁高效,对应用性能影响小
  • 内存占用:状态管理采用轻量级设计,内存占用低

10.4 维护成本

  • 类型安全:TypeScript 提供了良好的类型安全,减少运行时错误
  • 模块化设计:代码结构清晰,便于维护和扩展
  • 完整的文档:提供了详细的 API 文档和使用示例

11. 总结

本项目是一个功能完整、设计合理、易于使用的 Api 平台接口 TypeScript SDK。它提供了一套完整的客户端解决方案,包括 API 请求处理、签名机制、Token 管理、日志记录和错误处理等功能。SDK 采用了模块化设计,具有良好的扩展性和可维护性,同时支持多种环境和模块格式。 通过使用本 SDK,开发者可以快速集成 Api 平台接口,减少重复开发工作,提高开发效率和代码质量。SDK 提供了完整的 TypeScript 类型定义,支持 IDE 智能提示,同时具有良好的错误处理和日志记录机制,便于调试和问题定位。 本技术方案详细介绍了 SDK 的功能、技术选型、架构设计、核心模块实现、类型定义和使用方法等内容,为后续的开发和使用提供了全面的指导。