32 lines
997 B
Rust
32 lines
997 B
Rust
//
|
|
use kxio::{net::Response, print::Printer};
|
|
|
|
use crate::{e, s};
|
|
|
|
pub(crate) struct APIResult<T> {
|
|
pub(crate) text: String,
|
|
pub(crate) result: Result<T, kxio::net::Error>,
|
|
}
|
|
|
|
impl<T: for<'a> serde::Deserialize<'a>> APIResult<T> {
|
|
pub async fn new(response: kxio::net::Result<Response>, prt: &Printer) -> Self {
|
|
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| {
|
|
e!(prt, "{e}: {text}");
|
|
e
|
|
})
|
|
.map_err(kxio::net::Error::from);
|
|
Self { text, result }
|
|
}
|
|
Err(e) => Self {
|
|
text: s!(""),
|
|
result: Err(e),
|
|
},
|
|
}
|
|
}
|
|
}
|