From c488c4840588fd88fa840306c40ab99ebb3512b9 Mon Sep 17 00:00:00 2001 From: "Alex Pooley (@zuedev)" Date: Wed, 15 Jul 2026 13:15:57 +0100 Subject: implement caching for UEX data and create cache directory --- 174bg/discord-bot/.gitignore | 3 ++- 174bg/discord-bot/main.js | 50 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) (limited to '174bg') diff --git a/174bg/discord-bot/.gitignore b/174bg/discord-bot/.gitignore index 9b6ab89..511bcd0 100644 --- a/174bg/discord-bot/.gitignore +++ b/174bg/discord-bot/.gitignore @@ -1,2 +1,3 @@ /.env -/node_modules/ \ No newline at end of file +/node_modules/ +/uex-cache/ \ No newline at end of file diff --git a/174bg/discord-bot/main.js b/174bg/discord-bot/main.js index 7590d9c..30d2a1d 100644 --- a/174bg/discord-bot/main.js +++ b/174bg/discord-bot/main.js @@ -10,6 +10,12 @@ import { ButtonBuilder, ButtonStyle, } from "discord.js"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); const commands = [ { @@ -203,6 +209,13 @@ client.on(Events.ClientReady, async (readyClient) => { } catch (error) { console.error(error); } + + cacheUexData(); + + // every hour + setInterval(async () => { + await cacheUexData(); + }, 60 * 60 * 1000); // 1 hour }); client.on(Events.InteractionCreate, async (interaction) => { @@ -287,4 +300,41 @@ function sendMessageToLogsChannel(message) { function codewrap(language, content) { return "```" + language + "\n" + content + "\n```"; +} + +async function cacheUexData() { + const list = [ + "https://api.uexcorp.uk/2.0/commodities_raw_prices_all", + "https://api.uexcorp.uk/2.0/items_prices_all", + "https://api.uexcorp.uk/2.0/fuel_prices_all", + "https://api.uexcorp.uk/2.0/commodities_prices_all", + "https://api.uexcorp.uk/2.0/vehicles_purchases_prices_all", + "https://api.uexcorp.uk/2.0/vehicles_rentals_prices_all" + ]; + + const cacheDir = path.join(__dirname, "uex-cache"); + fs.mkdirSync(cacheDir, { recursive: true }); + + for (const url of list) { + try { + const response = await fetch(url); + + if (!response.ok) { + throw new Error(`Received status ${response.status}`); + } + + const data = await response.json(); + + if (data === null || typeof data !== "object") { + throw new Error("Response was not a JSON object/array"); + } + + // write to file + const filePath = path.join(cacheDir, `${url.split("/").pop()}.json`); + + fs.writeFileSync(filePath, JSON.stringify(data, null, 2)); + } catch (error) { + console.error(`Error fetching ${url}:`, error); + } + } } \ No newline at end of file -- cgit v1.2.3