Migrate baedernames to HashMap and display fetched names

This commit is contained in:
clerie 2024-07-20 19:13:54 +02:00
parent 49e8db169c
commit 5abbe686cf

View File

@ -10,6 +10,8 @@ use serde::{
Serialize, Serialize,
}; };
use std::collections::HashMap;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct TrafficDataThresholds { struct TrafficDataThresholds {
level: i64, level: i64,
@ -29,12 +31,7 @@ struct TrafficDataItem {
thresholds: Vec<TrafficDataThresholds>, thresholds: Vec<TrafficDataThresholds>,
} }
struct BaederNames { async fn get_baeder_names() -> Result<HashMap<String, String>, String> {
id: String,
name: String,
}
async fn get_baeder_names() -> Result<Vec<BaederNames>, String> {
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let baedernames_req = client.get(String::from("https://www.berlinerbaeder.de/baeder/sommerbaeder-auslastung/")) let baedernames_req = client.get(String::from("https://www.berlinerbaeder.de/baeder/sommerbaeder-auslastung/"))
@ -51,13 +48,13 @@ async fn get_baeder_names() -> Result<Vec<BaederNames>, String> {
let r = Regex::new(r#"<tr data-bath="(.+)" data-name="(.+)" data-address="#) let r = Regex::new(r#"<tr data-bath="(.+)" data-name="(.+)" data-address="#)
.map_err(|_err| String::from("Cannot parse regex"))?; .map_err(|_err| String::from("Cannot parse regex"))?;
let mut baedernames: Vec<BaederNames> = vec!{}; let mut baedernames= HashMap::new();
for c in r.captures_iter(baedernames_body.as_str()) { for c in r.captures_iter(baedernames_body.as_str()) {
baedernames.push(BaederNames { baedernames.insert(
id: c.get(1).unwrap().as_str().to_string(), c.get(1).unwrap().as_str().to_string(), // id
name: c.get(2).unwrap().as_str().to_string(), c.get(2).unwrap().as_str().to_string(), // name
}) );
} }
return Ok(baedernames); return Ok(baedernames);
@ -91,7 +88,14 @@ async fn main() {
} }
} }
let baedernames = get_baeder_names().await; // If baedernames cannot be fetched, ignore them
let baedernames = get_baeder_names().await.unwrap_or(HashMap::new());
println!("Baedernames:");
for (id, name) in baedernames {
println!("{id}: {name}");
}
println!("");
let app = Router::new() let app = Router::new()
.route("/", get(route_index)) .route("/", get(route_index))