Energiepreise/src/index.ts

72 lines
2.1 KiB
TypeScript

interface MarketSlice {
startTimestamp: Date;
endTimestamp: Date;
marketPrice: number;
unit: string;
}
interface MarketData {
object: string;
url: string;
data: MarketSlice[];
}
const TIME_FORMAT = Intl.DateTimeFormat(undefined, {
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
});
async function getMarketData(): Promise<MarketData> {
const request = await fetch("https://api.awattar.at/v1/marketdata");
const data = await request.json();
return {
object: data.object,
url: data.url,
data: data.data.map((slice) => {
return {
startTimestamp: new Date(slice.start_timestamp),
endTimestamp: new Date(slice.end_timestamp),
marketPrice: slice.marketprice,
unit: slice.unit,
};
}),
};
}
async function writeTable() {
const data = await getMarketData();
const table = document.createElement("table");
table.classList.add("table", "is-striped", "is-hoverable", "is-fullwidth");
const body = document.createElement("tbody");
for (const slice of data.data) {
const tr = document.createElement("tr");
const timeCell = document.createElement("td");
const priceCell = document.createElement("td");
// How green the price should be; ~100€/MWh seems to be a
// pretty expensive price, so that or worse is 100% red, while
// 0 or lower is 0% red
const redPercent = Math.max(Math.min(slice.marketPrice / 100, 1), 0);
console.info(redPercent);
timeCell.innerText = TIME_FORMAT.format(slice.startTimestamp);
priceCell.innerHTML = slice.marketPrice.toString();
priceCell.style.color = `color-mix(in lch, green, red ${
redPercent * 100
}%)`;
tr.appendChild(timeCell);
tr.appendChild(priceCell);
body.appendChild(tr);
}
table.appendChild(body);
document.body.appendChild(table);
}
document.addEventListener("DOMContentLoaded", writeTable);