2024-12-06 08:31:34 +00:00
|
|
|
//
|
2024-12-07 10:05:37 +00:00
|
|
|
use kxio::{net::Response, print::Printer};
|
2024-11-29 19:19:36 +00:00
|
|
|
|
|
|
|
use crate::{e, s};
|
2024-12-06 08:31:34 +00:00
|
|
|
|
2024-11-29 19:19:36 +00:00
|
|
|
pub struct APIResult<T> {
|
|
|
|
pub result: Result<T, kxio::net::Error>,
|
|
|
|
}
|
2024-12-06 08:31:34 +00:00
|
|
|
|
2024-11-29 19:19:36 +00:00
|
|
|
impl<T: for<'a> serde::Deserialize<'a>> APIResult<T> {
|
2024-12-07 10:05:37 +00:00
|
|
|
pub async fn new(response: kxio::net::Result<Response>, prt: &Printer) -> Self {
|
2024-11-29 19:19:36 +00:00
|
|
|
match response {
|
|
|
|
Ok(response) => {
|
|
|
|
let text = response.text().await.unwrap_or_default();
|
|
|
|
let text = if text.is_empty() { s!("null") } else { text };
|
|
|
|
let result = serde_json::from_str::<T>(&text)
|
|
|
|
.map_err(|e| e.to_string())
|
|
|
|
.map_err(|e| {
|
2024-12-07 10:05:37 +00:00
|
|
|
e!(prt, "{e}: {text}");
|
2024-11-29 19:19:36 +00:00
|
|
|
e
|
|
|
|
})
|
|
|
|
.map_err(kxio::net::Error::from);
|
2024-11-30 11:30:36 +00:00
|
|
|
Self { result }
|
2024-11-29 19:19:36 +00:00
|
|
|
}
|
2024-11-30 11:30:36 +00:00
|
|
|
Err(e) => Self { result: Err(e) },
|
2024-11-29 19:19:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|