Public
Cron
Runs every 1 days
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { blob } from "https://esm.town/v/std/blob";
import { fetch } from "https://esm.town/v/std/fetch";
import xml2js from "npm:xml2js";
async function fetchHistoricData() {
const currentDate = new Date();
const promises = [];
for (let i = 0; i < 30; i++) {
const date = new Date();
date.setDate(currentDate.getDate() - i);
const formattedDate = date.toISOString().split("T")[0];
const url =
`https://www.floatrates.com/historical-exchange-rates.html?operation=rates&pb_id=1462&page=historical¤cy_date=${formattedDate}&base_currency_code=JPY&format_type=xml`;
const fetchPromise = fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok " + response.statusText);
}
return response.text();
})
.then((xmlText) => {
// Parsing the XML text to a JavaScript object
const parser = new xml2js.Parser();
return parser.parseStringPromise(xmlText);
})
.then((result) => {
console.log(result.channel.item);
const parsedExchangeRates = result.channel.item.map((item) => ({
targetCurrency: item.targetCurrency[0],
exchangeRate: item.exchangeRate[0],
}));
return {
date: formattedDate,
rates: parsedExchangeRates,
};
})
.catch((error) => {
console.error(
"There has been a problem with your fetch operation:",
error,
);
return null;
});
promises.push(fetchPromise);
}
const exchangeRatesData = await Promise.all(promises);
const filteredErroredData = exchangeRatesData.filter((data) => data !== null);
const exchangeRates = {
data: filteredErroredData,
lastUpdated: currentDate.toISOString().split("T")[0],
};
return exchangeRates;
}
export default async function(interval: Interval) {
const history = await fetchHistoricData();
await blob.setJSON("daily", history);
return history;
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
July 2, 2024