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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@pddo/exchange-rate-sdk

v1.0.0

Published

TypeScript SDK for Exchange Rate API - 汇率API的TypeScript SDK

Readme

@pddo/exchange-rate-sdk

npm version TypeScript License: MIT

汇率API的TypeScript SDK,提供简洁易用的接口来访问实时汇率数据和货币转换功能。

✨ 特性

  • 🚀 TypeScript支持: 完整的类型定义,提供优秀的开发体验
  • 🌐 现代化API: 基于Promise的异步API,支持async/await
  • 🛡️ 错误处理: 完善的错误处理机制和自定义错误类型
  • 高性能: 内置请求超时和批量操作支持
  • 🔧 可配置: 灵活的配置选项,支持自定义域名和请求头
  • 📦 轻量级: 零依赖,体积小巧
  • 🌍 多环境: 支持Node.js和浏览器环境

📦 安装

# 使用 npm
npm install @pddo/exchange-rate-sdk

# 使用 yarn
yarn add @pddo/exchange-rate-sdk

# 使用 pnpm
pnpm add @pddo/exchange-rate-sdk

# 使用 bun
bun add @pddo/exchange-rate-sdk

🚀 快速开始

基础用法

import { ExchangeRateSDK } from '@pddo/exchange-rate-sdk';

// 创建SDK实例
const sdk = new ExchangeRateSDK();

// 获取汇率
const rate = await sdk.getExchangeRate('USD', 'EUR');
console.log(`1 USD = ${rate.data} EUR`);

// 货币转换
const result = await sdk.convertCurrency('USD', 'CNY', 100);
console.log(`100 USD = ${result.data} CNY`);

使用便捷函数

import { createExchangeRateSDK } from '@pddo/exchange-rate-sdk';

const sdk = createExchangeRateSDK({
  baseURL: 'https://your-api.com',
  timeout: 5000,
  debug: true
});

自定义配置

import { ExchangeRateSDK } from '@pddo/exchange-rate-sdk';

const sdk = new ExchangeRateSDK({
  baseURL: 'https://exchange-api.pd.do',
  timeout: 10000,
  headers: {
    'X-Custom-Header': 'value'
  },
  debug: false
});

📖 API 文档

ExchangeRateSDK

构造函数

new ExchangeRateSDK(options?: ExchangeRateSDKOptions)

配置选项

interface ExchangeRateSDKOptions {
  baseURL?: string;        // API基础URL,默认: 'https://exchange-api.pd.do'
  timeout?: number;        // 请求超时时间(毫秒),默认: 10000
  headers?: Record<string, string>; // 自定义请求头
  debug?: boolean;         // 是否启用调试模式,默认: false
}

主要方法

1. 获取特定基准货币的所有汇率

async getCurrencyRates(currency: string): Promise<CurrencyRatesResponse>

示例:

const rates = await sdk.getCurrencyRates('USD');
console.log(rates.data.EUR); // 美元对欧元的汇率
console.log(rates.data.CNY); // 美元对人民币的汇率

2. 获取两种货币之间的汇率

async getExchangeRate(baseCurrency: string, targetCurrency: string): Promise<RateResponse>

示例:

const rate = await sdk.getExchangeRate('EUR', 'USD');
console.log(`1 EUR = ${rate.data} USD`);

3. 进行货币转换

async convertCurrency(baseCurrency: string, targetCurrency: string, amount: number): Promise<ConversionResponse>

示例:

const result = await sdk.convertCurrency('GBP', 'JPY', 50);
console.log(`50 GBP = ${result.data} JPY`);
console.log(`汇率: ${result.rate}`);

4. 批量获取汇率

async getBatchRates(pairs: Array<[string, string]>): Promise<Array<RateResponse>>

示例:

const rates = await sdk.getBatchRates([
  ['USD', 'EUR'],
  ['USD', 'CNY'],
  ['EUR', 'JPY']
]);

rates.forEach(rate => {
  console.log(`${rate.base_code} -> ${rate.target_code}: ${rate.data}`);
});

5. 批量货币转换

async batchConvert(conversions: Array<{from: string, to: string, amount: number}>): Promise<Array<ConversionResponse>>

示例:

const results = await sdk.batchConvert([
  { from: 'USD', to: 'EUR', amount: 100 },
  { from: 'EUR', to: 'CNY', amount: 50 },
  { from: 'GBP', to: 'JPY', amount: 25 }
]);

results.forEach(result => {
  console.log(`${result.base_code} -> ${result.target_code}: ${result.data}`);
});

6. 手动更新汇率(需要密码)

async updateRates(password: string): Promise<UpdateResponse>

示例:

try {
  const result = await sdk.updateRates('your-password');
  console.log('汇率更新成功:', result.message);
} catch (error) {
  console.error('更新失败:', error.message);
}

工具方法

获取常用货币列表

const currencies = sdk.getCommonCurrencies();
console.log(currencies); // ['USD', 'EUR', 'CNY', 'JPY', ...]

验证货币代码格式

console.log(sdk.isValidCurrencyFormat('USD')); // true
console.log(sdk.isValidCurrencyFormat('us'));  // false

格式化货币代码

console.log(sdk.formatCurrency('usd')); // 'USD'
console.log(sdk.formatCurrency(' eur ')); // 'EUR'

🔧 高级用法

错误处理

import { ExchangeRateAPIError } from '@pddo/exchange-rate-sdk';

try {
  const rate = await sdk.getExchangeRate('INVALID', 'USD');
} catch (error) {
  if (error instanceof ExchangeRateAPIError) {
    console.error('API错误:', error.message);
    console.error('状态码:', error.status);
    console.error('错误代码:', error.code);
  } else {
    console.error('未知错误:', error);
  }
}

动态配置更新

// 更新配置
sdk.updateConfig({
  baseURL: 'https://new-api.com',
  debug: true,
  headers: {
    'Authorization': 'Bearer token'
  }
});

自定义HTTP客户端

import { HttpClient } from '@pddo/exchange-rate-sdk';

const client = new HttpClient({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  debug: true
});

// 直接使用HTTP客户端
const response = await client.get('/custom-endpoint');

📝 响应类型

CurrencyRatesResponse

interface CurrencyRatesResponse {
  message: string;
  data: Record<string, number>; // 货币代码 -> 汇率
}

RateResponse

interface RateResponse {
  message: string;
  data: number;           // 汇率
  base_code: string;      // 基准货币
  target_code: string;    // 目标货币
}

ConversionResponse

interface ConversionResponse {
  message: string;
  data: number;           // 转换后的金额
  rate: number;           // 使用的汇率
  base_code: string;      // 基准货币
  target_code: string;    // 目标货币
}

🌍 支持的货币

SDK支持所有ISO 4217标准的货币代码,常用货币包括:

  • 主要货币: USD, EUR, CNY, JPY, GBP, AUD, CAD, CHF
  • 亚洲货币: HKD, SGD, KRW, INR, THB, IDR, MYR, PHP
  • 欧洲货币: SEK, NOK, DKK, PLN, HUF, CZK, RON
  • 其他货币: MXN, BRL, ZAR, TRY, RUB, AED, SAR

🛠 开发

# 克隆仓库
git clone https://github.com/catpddo/exchange-rate.git
cd exchange-rate/sdk

# 安装依赖
bun install

# 开发模式
bun run dev

# 构建
bun run build

# 类型检查
bun run type-check

📄 许可证

MIT License - 详见 LICENSE 文件

🤝 贡献

欢迎提交 Issue 和 Pull Request!

🔗 相关链接

📞 支持

如有问题或建议,请:

  1. 查看 API文档
  2. 提交 GitHub Issue
  3. 发送邮件至 [email protected]