69 lines
2.0 KiB
JavaScript
69 lines
2.0 KiB
JavaScript
import ky from "ky";
|
|
import logger from "../utils/logger.js"
|
|
|
|
// Global object to store the latest crypto prices
|
|
const cryptoPrices = {
|
|
btc: null,
|
|
ltc: null,
|
|
xmr: null,
|
|
lastUpdated: null,
|
|
};
|
|
|
|
/**
|
|
* Fetch crypto prices from the CoinGecko API and update the global `cryptoPrices` object.
|
|
*/
|
|
const fetchCryptoPrices = async () => {
|
|
try {
|
|
const url =
|
|
"https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,litecoin,monero&vs_currencies=gbp";
|
|
|
|
// Fetch using Ky with automatic JSON parsing
|
|
const data = await ky.get(url).json();
|
|
|
|
// Update the stored crypto prices
|
|
cryptoPrices.btc = data.bitcoin?.gbp ?? null;
|
|
cryptoPrices.ltc = data.litecoin?.gbp ?? null;
|
|
cryptoPrices.xmr = data.monero?.gbp ?? null;
|
|
cryptoPrices.lastUpdated = new Date().toISOString();
|
|
|
|
logger.info("✅ Crypto prices updated", { cryptoPrices });
|
|
} catch (error) {
|
|
logger.error("❌ Error fetching crypto prices", {
|
|
message: error.message || "Unknown error",
|
|
});
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Starts the automatic crypto price updater.
|
|
* @param {number} interval - Update interval in seconds.
|
|
*/
|
|
const startCryptoPriceUpdater = (interval) => {
|
|
logger.info(`🚀 Starting crypto price updater (every ${interval} seconds)`);
|
|
fetchCryptoPrices(); // Fetch immediately
|
|
setInterval(fetchCryptoPrices, interval * 1000); // Fetch periodically
|
|
};
|
|
|
|
/**
|
|
* API Route: Get the latest crypto prices.
|
|
* @route GET /api/crypto
|
|
*/
|
|
const getCryptoPrices = async (req, res) => {
|
|
try {
|
|
res.json({
|
|
success: true,
|
|
prices: cryptoPrices,
|
|
});
|
|
} catch (error) {
|
|
logger.error("❌ Error getting crypto prices", {
|
|
message: error.message || "Unknown error",
|
|
});
|
|
res.status(500).json({ success: false, error: "Internal Server Error" });
|
|
}
|
|
};
|
|
|
|
const returnCryptoPrices = () => {
|
|
return cryptoPrices;
|
|
};
|
|
|
|
export { startCryptoPriceUpdater, getCryptoPrices, returnCryptoPrices }; |