metart43-getoctopusenergyrates.web.val.run
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
import { renderTable } from "https://esm.town/v/metart43/renderTable";
import { fetch } from "https://esm.town/v/std/fetch";
import process from "node:process";
// Declare the function as async and export it
export const htmlExample = async () => {
const url =
"https://api.octopus.energy/v1/products/AGILE-FLEX-22-11-25/electricity-tariffs/E-1R-AGILE-FLEX-22-11-25-C/standard-unit-rates/";
try {
const response = await fetch(url, {
headers: {
"Authorization": "Basic " + btoa(process.env.OCTOPUS_ENERGY_API_KEY || ""),
},
});
const data = await response.json();
const rates = data.results;
const processedData = rates.map((rate) => ({
date: rate.valid_from,
value: rate.value_inc_vat,
}));
function filterDataForDate(data, date) {
return data.filter((d) => {
const entryDate = new Date(d.date).toISOString().split("T")[0];
return entryDate === date;
});
}
const todaysDate = new Date().toISOString().split("T")[0];
const todaysRates = filterDataForDate(processedData, todaysDate);
console.log({ todaysRates });
const graph = renderTable(todaysRates);
// Assuming Response is from a Fetch API context, like in service workers or Deno
return new Response(graph, {
headers: {
"Content-Type": "text/html",
},
});
} catch (e) {
console.error("error getting rates", e.message);
// Handle errors appropriately in your context, maybe returning an error Response
return new Response("Error retrieving data", { status: 500 });
}
};
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!
May 10, 2024