argy-usd
Version:
A simple and efficient library for fetching Argentine dollar exchange rates and performing currency conversions.
138 lines (134 loc) • 4.36 kB
JavaScript
// src/api/bluelytics.ts
import axios from "axios";
async function fetchFromBluelytics(dollarType = "all") {
try {
const response = await axios.get("https://api.bluelytics.com.ar/v2/latest");
const data = response.data;
const timestamp = new Date(data.last_update);
const dollarTypes = {
oficial: data.oficial,
blue: data.blue
};
if (dollarType === "all") {
return Object.entries(dollarTypes).map(([name, data2]) => ({
name,
buy: data2.value_buy,
sell: data2.value_sell,
source: "bluelytics",
timestamp
}));
}
return [{
name: dollarType,
buy: dollarTypes[dollarType].value_buy,
sell: dollarTypes[dollarType].value_sell,
source: "bluelytics",
timestamp
}];
} catch (error) {
console.error("Error fetching from Bluelytics:", error);
throw error;
}
}
// src/api/dolarapi.ts
import axios2 from "axios";
async function fetchFromDolarApi(dollarType = "all") {
try {
const baseUrl = "https://dolarapi.com/v1/dolares";
const url = dollarType === "all" ? baseUrl : `${baseUrl}/${dollarType}`;
const response = await axios2.get(url);
const data = response.data;
const transformItem = (item) => ({
name: item.nombre.toLowerCase(),
buy: item.compra || 0,
sell: item.venta || 0,
source: "dolarapi",
timestamp: new Date(item.fechaActualizacion)
});
return Array.isArray(data) ? data.map(transformItem) : [transformItem(data)];
} catch (error) {
console.error("Error fetching from DolarAPI:", error);
throw error;
}
}
// src/utils.ts
var cache = {};
function cacheResult(key, data) {
cache[key] = {
data,
timestamp: Date.now()
};
}
function getCached(key) {
const entry = cache[key];
if (!entry) return null;
const age = (Date.now() - entry.timestamp) / 1e3;
return age < 60 ? entry.data : null;
}
// src/index.ts
var sources = {
bluelytics: (dollarType) => fetchFromBluelytics(dollarType),
dolarapi: (dollarType) => fetchFromDolarApi(dollarType)
};
async function getDollarRates({ source = "bluelytics", cache: cache2 = true, dollarType = "all" } = {}) {
if (source === "bluelytics" && dollarType !== "all" && dollarType !== "oficial" && dollarType !== "blue") {
throw new Error(`Dollar type '${dollarType}' is not supported by Bluelytics. Supported types: 'all', 'oficial', 'blue'`);
}
if (source === "dolarapi" && dollarType !== "all" && !["blue", "oficial", "bolsa", "cll", "mayorista", "cripto", "tarjeta"].includes(dollarType)) {
throw new Error(`Dollar type '${dollarType}' is not supported by DolarAPI. Supported types: 'all', 'blue', 'oficial', 'bolsa', 'cll', 'mayorista', 'cripto', 'tarjeta'`);
}
const cached = getCached(source + dollarType);
if (cached && cache2) return cached;
const data = await sources[source](dollarType);
cacheResult(source + dollarType, data);
return data;
}
async function convertUsdToArs(amount, rateType, type, source = "bluelytics") {
const rates = await getDollarRates({ source });
const quote = rates.find((r) => r.name.toLowerCase().includes(rateType.toLowerCase()));
if (!quote) throw new Error("D\xF3lar no encontrado");
return type === "buy" ? amount * quote.buy : amount * quote.sell;
}
async function convertArsToUsd(amount, rateType, type, source = "bluelytics") {
const rates = await getDollarRates({ source });
const quote = rates.find((r) => r.name.toLowerCase().includes(rateType.toLowerCase()));
if (!quote) throw new Error("D\xF3lar no encontrado");
return type === "buy" ? amount / quote.sell : amount / quote.buy;
}
function pollDollarRates(options = {}) {
const {
interval = 6e4,
// Default to 1 minute
onUpdate,
onError,
...getDollarRatesOptions
} = options;
let isPolling = true;
const poll = async () => {
if (!isPolling) return;
try {
const rates = await getDollarRates(getDollarRatesOptions);
if (onUpdate && isPolling) {
onUpdate(rates);
}
} catch (error) {
if (onError && isPolling) {
onError(error);
}
} finally {
if (isPolling) {
setTimeout(poll, interval);
}
}
};
poll();
return () => {
isPolling = false;
};
}
export {
convertArsToUsd,
convertUsdToArs,
getDollarRates,
pollDollarRates
};