central-bank-russia
v1.0.1
Published
Library for fetching currency rates from Central Bank of Russia
Downloads
274
Readme
Central Bank of Russia (CBR) Rates
A lightweight, type-safe TypeScript library for fetching and processing official currency exchange rates from the Central Bank of Russia (CBR) API.
Features
- Direct API Integration: Fetches real-time data from
cbr.ru. - Automatic Encoding: Built-in Windows-1251 (CP1251) decoding for CBR's XML responses.
- Strict Typing: Full TypeScript support with enums for currency codes.
- Strict Mode: Optional strict mode that throws errors if a currency is missing, ensuring runtime safety.
- Conversion Utilities: Easy-to-use methods for converting between foreign currencies and Russian Rubles (RUB).
Installation
npm install central-bank-russia
# or
bun add central-bank-russiaQuick Start
import { CBR } from 'central-bank-russia';
const cbr = new CBR(); // Strict mode enabled by default
// Get USD rate
const usd = await cbr.getCurrency('USD');
console.log(`1 USD = ${usd.course} RUB`);
// Convert 100 USD to Rubles
const rubles = usd.convert(100);
console.log(`100 USD is ${rubles} RUB`);
// Convert 1000 Rubles to USD
const amountInUsd = usd.convertFromRubles(1000);
console.log(`1000 RUB is ${amountInUsd.toFixed(2)} USD`);Detailed Usage
Strict vs Non-Strict Mode
By default, the CBR class operates in Strict Mode. This provides:
- Autocomplete for all currency codes (USD, EUR, etc.).
- Guaranteed return values (throws an error if the currency is not found in the CBR response).
// Non-strict mode
const cbr = new CBR(false);
const rate = await cbr.getCurrency('ANY_CODE'); // returns Currency | undefinedFetching Multiple Rates
const currencies = await cbr.getCurrencies();
currencies.forEach(cur => {
console.log(`${cur.code}: ${cur.course}`);
});Manual Cache Refresh
The library caches the rates after the first fetch. You can manually refresh them:
await cbr.refresh();Recommended Resources
For more detailed metadata about currencies (names in multiple languages, symbols, countries, etc.), we highly recommend using:
👉 currency-codes-ts — A comprehensive database of ISO 4217 currency codes and metadata.
License
MIT
