uptime-kuma-dashboard/src/api/client.rs
2026-01-21 12:34:50 -04:00

51 lines
1.5 KiB
Rust

use std::time::Duration;
use anyhow::Result;
use reqwest::blocking::Client;
use crate::{
api::endpoints::UptimeKumaEndpoints,
data::{self, heartbeat::HeartbeatResponse, status_page::model::StatusPageResponse}, i18n::t,
};
#[derive(Debug, Clone)]
pub struct UptimeKumaClient {
client: Client,
}
impl UptimeKumaClient {
pub fn new() -> Self {
let client = Client::builder().connect_timeout(Duration::from_secs(10)).timeout(Duration::from_secs(30)).build().unwrap_or_else(|_| panic!("{}", t("http-build-error")));
Self {
client,
}
}
pub fn fetch_heartbeat(&self, endpoints: &UptimeKumaEndpoints) -> Result<HeartbeatResponse> {
self.fetch_and_parse(endpoints.heartbeat_url(), data::heartbeat::parse_response)
}
pub fn fetch_status_page(&self, endpoints: &UptimeKumaEndpoints) -> Result<StatusPageResponse> {
self.fetch_and_parse(
endpoints.status_page_url(),
data::status_page::parse_response,
)
}
fn fetch_and_parse<T, F>(&self, url: String, parser: F) -> Result<T>
where
F: FnOnce(&str) -> Result<T>,
{
let response = self.client.get(url.clone()).send()?;
if response.status().is_success() {
let json_text = response.text()?;
parser(&json_text)
} else {
Err(anyhow::anyhow!(
"URL: {}, Error: {}",
url,
response.status()
))
}
}
}