Skip to content

chengzuopeng/exchange-rate-sdk

Repository files navigation

Exchange Rate SDK

一个轻量级、跨平台的汇率查询的 JavaScript SDK,支持浏览器和 Node.js 环境运行。

A lightweight, cross-platform exchange rate JavaScript SDK for browser and Node.js.

🎮 在线演示 / Playground

体验 SDK 的所有功能: 👉 https://chengzuopeng.github.io/exchange-rate-sdk/

✨ 特性 / Features

  • 🌍 跨平台支持 - 同时支持浏览器和 Node.js 环境
  • 💾 智能缓存 - 浏览器使用 localStorage + 内存双层缓存,Node.js 使用内存缓存
  • 🔄 自动重试 - 网络请求失败时自动重试,支持指数退避
  • 📦 零运行时依赖 - 不依赖任何第三方库
  • 🌐 离线货币信息 - 内置 168 种货币信息,离线可查
  • 🔍 货币搜索 - 支持中英文搜索货币

📦 安装 / Installation

yarn add exchange-rate-sdk
# or
npm install exchange-rate-sdk

🚀 快速开始 / Quick Start

import { ExchangeRateSDK } from 'exchange-rate-sdk';

const client = new ExchangeRateSDK();
const rate = await client.getRate('USD', 'CNY');
console.log(`1 USD = ${rate} CNY`);

⚙️ 配置选项 / Configuration

import { ExchangeRateSDK } from 'exchange-rate-sdk';

const client = new ExchangeRateSDK({
  // 缓存过期时间(毫秒),默认 24 小时
  cacheTTL: 24 * 60 * 60 * 1000,
  
  // 请求超时时间(毫秒),默认 10 秒
  timeout: 10000,

  // 最大重试次数,默认 3 次
  maxRetries: 3,
  
  // 重试延迟基数(毫秒),默认 1000,使用指数退避
  retryDelay: 1000,
});

📖 API 文档 / API Reference

getRate(from: string, to: string): Promise<number>

获取两种货币之间的汇率。

const rate = await client.getRate('USD', 'CNY');
// => 7.25

convert(amount: number, from: string, to: string): Promise<ConvertResult>

货币金额转换。

const result = await client.convert(100, 'USD', 'CNY');
// => { amount: 725, from: 'USD', to: 'CNY', rate: 7.25 }

getRates(base: string): Promise<RatesResponse>

获取某货币对所有其他货币的汇率。

const rates = await client.getRates('USD');
// => { base: 'USD', date: '2024-01-01', rates: { CNY: 7.25, EUR: 0.92, ... } }

getCurrency(code: string): Currency | undefined

获取单个货币的详细信息(离线可用)。

const info = client.getCurrency('USD');
// => { code: 'USD', name: 'United States Dollar', name_cn: '美元', 
//      country: 'United States', country_cn: '美国' }

getCurrencies(): Currency[]

获取所有支持的货币列表(离线可用)。

const currencies = client.getCurrencies();
// => [{ code: 'USD', ... }, { code: 'CNY', ... }, ...]

searchCurrency(keyword: string): Currency[]

搜索货币,支持中英文(离线可用)。

// 按货币代码搜索
const results1 = client.searchCurrency('USD');

// 按英文名称搜索
const results2 = client.searchCurrency('Dollar');

// 按中文名称搜索
const results3 = client.searchCurrency('人民币');
// => [{ code: 'CNY', name_cn: '人民币', ... }]

clearCache(): void

清空所有缓存。

client.clearCache();

setCacheTTL(ttl: number): void

更新缓存过期时间。

client.setCacheTTL(60 * 60 * 1000); // 设置为 1 小时

📋 类型定义 / Type Definitions

interface ExchangeRateSDKOptions {
  cacheTTL?: number;      // 缓存过期时间(毫秒)
  timeout?: number;       // 请求超时(毫秒)
  maxRetries?: number;    // 最大重试次数
  retryDelay?: number;    // 重试延迟基数
}

interface Currency {
  code: string;           // 货币代码 e.g. 'USD'
  name: string;           // 英文名称
  name_cn: string;        // 中文名称
  country: string;        // 国家/地区英文名
  country_cn: string;     // 国家/地区中文名
}

interface RatesResponse {
  base: string;           // 基准货币
  date: string;           // 汇率日期
  rates: Record<string, number>;  // 汇率映射
}

interface ConvertResult {
  amount: number;         // 转换后金额
  from: string;           // 源货币
  to: string;             // 目标货币
  rate: number;           // 使用的汇率
}

❌ 错误处理 / Error Handling

SDK 使用统一的错误类型,所有错误都包含 code 属性:

import { ExchangeRateSDK, isSDKError } from 'exchange-rate-sdk';

const client = new ExchangeRateSDK();

try {
  await client.getRate('INVALID', 'USD');
} catch (error) {
  if (isSDKError(error)) {
    switch (error.code) {
      case 'INVALID_CURRENCY_CODE':
        console.error('无效的货币代码');
        break;
      case 'NETWORK_ERROR':
        console.error('网络请求失败');
        break;
      case 'TIMEOUT_ERROR':
        console.error('请求超时');
        break;
      case 'API_ERROR':
        console.error('API 返回错误');
        break;
      default:
        console.error('未知错误');
    }
  }
}

错误代码 / Error Codes

错误代码 说明
INVALID_CURRENCY_CODE 无效的货币代码(不在支持列表中)
NETWORK_ERROR 网络请求失败
TIMEOUT_ERROR 请求超时
API_ERROR API 返回错误或响应格式无效
PARSE_ERROR 数据解析失败
UNKNOWN_ERROR 未知错误

🔄 重试机制 / Retry Mechanism

SDK 内置了智能重试机制:

  • 可重试的情况

    • 网络错误
    • 请求超时
    • HTTP 5xx 服务器错误
    • HTTP 429 请求过多
  • 重试策略:使用指数退避算法,每次重试延迟加倍

const client = new ExchangeRateSDK({
  maxRetries: 3,      // 最多重试 3 次
  retryDelay: 1000,   // 第一次重试等待 1 秒,第二次 2 秒,第三次 4 秒
});

💾 缓存机制 / Caching

浏览器环境

  • 使用 localStorage + 内存双层缓存
  • localStorage 持久化存储,刷新页面后仍然有效
  • 内存缓存提供更快的访问速度

Node.js 环境

  • 使用内存缓存(Map)
  • 进程重启后缓存失效

缓存键格式

缓存使用 exchange_rate_sdk_rates_{CURRENCY_CODE} 格式存储。

🌐 支持的货币 / Supported Currencies

SDK 内置了 168 种货币信息,包括:

  • 主要货币:USD, EUR, GBP, JPY, CNY 等
  • 各国法定货币
  • 部分虚拟货币和特别提款权 (SDR)

使用 getCurrencies() 方法获取完整列表。

🛠️ 开发 / Development

# 安装依赖
yarn install

# 构建
yarn build

# 运行测试
yarn test

# 测试覆盖率
yarn test:coverage

📝 更新日志 / Changelog

查看完整的版本变更记录:CHANGELOG.md

📄 许可证 / License

ISC

About

轻量级的汇率查询的 JavaScript SDK,支持浏览器和 Node.js 环境运行。

Topics

Resources

License

Stars

Watchers

Forks

Packages