From 349e0cf3ff6aba4d2c0187b114c05f77a0952b31 Mon Sep 17 00:00:00 2001 From: Marco De Araujo Date: Mon, 5 Jan 2026 13:51:55 -0400 Subject: [PATCH] Refactoring --- src/api/client.rs | 29 ++++++++++++++++++----------- src/api/endpoints.rs | 22 ++++++++++++++++++++-- src/ui/app.rs | 2 +- 3 files changed, 39 insertions(+), 14 deletions(-) diff --git a/src/api/client.rs b/src/api/client.rs index acb68ae..eb3032f 100644 --- a/src/api/client.rs +++ b/src/api/client.rs @@ -19,23 +19,30 @@ impl UptimeKumaClient { } pub fn fetch_heartbeat(&self, endpoints: &UptimeKumaEndpoints) -> Result { - let response = self.client.get(endpoints.heartbeat_url()).send()?; - - if response.status().is_success() { - let json_text = response.text()?; - data::heartbeat::parse_response(&json_text) - } else { - return Err(anyhow::anyhow!(response.status())); - } + self.fetch_and_parse(endpoints.heartbeat_url(), data::heartbeat::parse_response) } pub fn fetch_status_page(&self, endpoints: &UptimeKumaEndpoints) -> Result { - let response = self.client.get(endpoints.status_page_url()).send()?; + self.fetch_and_parse( + endpoints.status_page_url(), + data::status_page::parse_response, + ) + } + + fn fetch_and_parse(&self, url: String, parser: F) -> Result + where + F: FnOnce(&str) -> Result, + { + let response = self.client.get(url.clone()).send()?; if response.status().is_success() { let json_text = response.text()?; - data::status_page::parse_response(&json_text) + parser(&json_text) } else { - return Err(anyhow::anyhow!(response.status())); + Err(anyhow::anyhow!( + "URL: {}, Error: {}", + url, + response.status() + )) } } } diff --git a/src/api/endpoints.rs b/src/api/endpoints.rs index 884472c..9004f3d 100644 --- a/src/api/endpoints.rs +++ b/src/api/endpoints.rs @@ -16,10 +16,28 @@ impl UptimeKumaEndpoints { } pub fn heartbeat_url(&self) -> String { - format!("{}api/status-page/heartbeat/{}", self.base_url, self.slug) + let mut url = self.get_url(); + url.path_segments_mut() + .unwrap() + .push("heartbeat") + .push(&self.slug); + url.to_string() } pub fn status_page_url(&self) -> String { - format!("{}api/status-page/{}", self.base_url, self.slug) + let mut url = self.get_url(); + url.path_segments_mut() + .unwrap() + .push(&self.slug); + url.to_string() + } + + fn get_url(&self) -> Url { + let mut url = self.base_url.clone(); + url.path_segments_mut() + .unwrap() + .push("api") + .push("status-page"); + url } } diff --git a/src/ui/app.rs b/src/ui/app.rs index 8403362..18fa818 100644 --- a/src/ui/app.rs +++ b/src/ui/app.rs @@ -188,7 +188,7 @@ impl App { } Err(e) => { let mut error = HashMap::new(); - error.insert("error", e.root_cause().to_string()); + error.insert("error", e.to_string()); self.state.error_message = Some(t_with_args("update-fail", &error)); } }