UNPKG

argy-usd

Version:

A simple and efficient library for fetching Argentine dollar exchange rates and performing currency conversions.

178 lines (172 loc) 6.19 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { convertArsToUsd: () => convertArsToUsd, convertUsdToArs: () => convertUsdToArs, getDollarRates: () => getDollarRates, pollDollarRates: () => pollDollarRates }); module.exports = __toCommonJS(index_exports); // src/api/bluelytics.ts var import_axios = __toESM(require("axios"), 1); async function fetchFromBluelytics(dollarType = "all") { try { const response = await import_axios.default.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 var import_axios2 = __toESM(require("axios"), 1); async function fetchFromDolarApi(dollarType = "all") { try { const baseUrl = "https://dolarapi.com/v1/dolares"; const url = dollarType === "all" ? baseUrl : `${baseUrl}/${dollarType}`; const response = await import_axios2.default.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; }; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { convertArsToUsd, convertUsdToArs, getDollarRates, pollDollarRates });