Automatische DWD Abfrage
Crontab hinzugefügt und automatische DWD Abfrage jeden Monat eingerichtet.
This commit is contained in:
73
src/cronjobs/update-dwd-klimafaktoren.ts
Normal file
73
src/cronjobs/update-dwd-klimafaktoren.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { prisma } from "@ibcornelsen/database";
|
||||
import moment from "moment";
|
||||
import csv from "csvtojson"
|
||||
|
||||
// Als erstes schauen wir, welches das letzte Jahr ist, für das wir einen Verbrauchsausweis haben.
|
||||
// Das machen wir, indem wir die Ausweise nach Jahr und Monat sortieren und dann den letzten Eintrag nehmen.
|
||||
const newestDate = await prisma.klimafaktoren.findFirst({
|
||||
orderBy: [
|
||||
{
|
||||
year: "desc",
|
||||
},
|
||||
{
|
||||
month: "desc",
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
if (!newestDate) {
|
||||
console.error("No last year found!")
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// Jetzt müssen wir abfragen, welche neuen Dateien es beim Deutschen Wetterdienst gibt.
|
||||
// https://opendata.dwd.de/climate_environment/CDC/derived_germany/techn/monthly/climate_correction_factor/recent/
|
||||
// Weil die Antwort in HTML ist und wir keinen Bock haben das alles zu parsen, versuchen wir einfach die neueste Datei abzufragen.
|
||||
// Das format des DWD ist wie folgt: KF_20221101_20231031.csv
|
||||
// Der Monat bei moment und in der Datenbank ist nullbasiert, also 0 = Januar, 11 = Dezember.
|
||||
const currentDate = moment().set("month", newestDate.month).set("year", newestDate.year).set("date", 1);
|
||||
|
||||
|
||||
const lastYearString = currentDate.clone().add(1, "month").startOf("month").format("YYYYMMDD");
|
||||
const nextYearString = currentDate.clone().add(1, "year").endOf("month").format("YYYYMMDD");
|
||||
|
||||
const filename = `KF_${lastYearString}_${nextYearString}.csv`
|
||||
|
||||
const url = "https://opendata.dwd.de/climate_environment/CDC/derived_germany/techn/monthly/climate_correction_factor/recent/"
|
||||
|
||||
const response = await fetch(`${url}${filename}`)
|
||||
|
||||
if (response.status !== 200) {
|
||||
console.error(`Could not fetch ${url}${filename}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const parser = csv({
|
||||
noheader: false,
|
||||
output: "json",
|
||||
delimiter: ";",
|
||||
})
|
||||
|
||||
const data: {
|
||||
DatAnf: string,
|
||||
DatEnd: string,
|
||||
PLZ: string,
|
||||
KF: string
|
||||
}[] = await parser.fromString(await response.text())
|
||||
|
||||
const year = currentDate.clone().add(1, "month").year();
|
||||
const month = currentDate.clone().add(1, "month").month();
|
||||
|
||||
const result = await prisma.klimafaktoren.createMany({
|
||||
data: data.map((row) => {
|
||||
return {
|
||||
year,
|
||||
month,
|
||||
klimafaktor: parseFloat(row.KF),
|
||||
plz: row.PLZ,
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
console.log(`Updated ${result.count} rows!`)
|
||||
Reference in New Issue
Block a user