v3.accords-library.com/scripts/download-currencies.mjs

49 lines
1.4 KiB
JavaScript
Raw Normal View History

2024-07-13 09:42:28 +00:00
// @ts-check
2024-06-02 07:27:30 +00:00
import { writeFileSync, readFileSync, existsSync } from "fs";
2024-02-24 17:42:52 +00:00
2024-07-13 09:42:28 +00:00
const OPEN_EXCHANGE_FOLDER = `${process.cwd()}/src/dist/openExchange`;
2024-06-02 07:27:30 +00:00
const RATE_JSON_PATH = `${OPEN_EXCHANGE_FOLDER}/rates.json`;
const CURRENCIES_JSON_PATH = `${OPEN_EXCHANGE_FOLDER}/currencies.json`;
const ONE_DAY_IN_MS = 1_000 * 60 * 60 * 24;
if (existsSync(RATE_JSON_PATH)) {
const rateBuffer = readFileSync(RATE_JSON_PATH, { encoding: "utf-8" });
const rateJSON = JSON.parse(rateBuffer);
const timestamp = rateJSON.timestamp * 1000;
const diff = Date.now() - timestamp;
if (diff < ONE_DAY_IN_MS) {
console.log("Currencies and rates are already up to date");
process.exit();
}
}
2024-02-24 17:42:52 +00:00
2024-07-13 09:42:28 +00:00
if (!process.env.OER_APP_ID) {
throw new Error("Missing OER_APP_ID env variable");
}
const ratesUrl = `https://openexchangerates.org/api/latest.json?app_id=${process.env.OER_APP_ID}`;
2024-02-24 17:42:52 +00:00
const currenciesUrl = `https://openexchangerates.org/api/currencies.json?app_id=${
2024-07-13 09:42:28 +00:00
process.env.OER_APP_ID
2024-02-24 17:42:52 +00:00
}`;
const rates = await fetch(ratesUrl);
if (rates.ok) {
2024-06-02 07:27:30 +00:00
writeFileSync(RATE_JSON_PATH, await rates.text(), {
2024-02-24 17:42:52 +00:00
encoding: "utf-8",
});
} else {
console.error("Failed to get the rates", rates.status, rates.statusText);
}
const currencies = await fetch(currenciesUrl);
if (currencies.ok) {
2024-06-02 07:27:30 +00:00
writeFileSync(CURRENCIES_JSON_PATH, await currencies.text(), {
2024-03-02 19:35:36 +00:00
encoding: "utf-8",
});
2024-02-24 17:42:52 +00:00
} else {
2024-03-02 19:35:36 +00:00
console.error("Failed to get the currencies", currencies.status, currencies.statusText);
2024-02-24 17:42:52 +00:00
}