2022-05-15 10:30:15 +02:00
|
|
|
use std::convert::Infallible;
|
|
|
|
use std::ops::FromResidual;
|
|
|
|
|
|
|
|
use seed::fetch::{FetchError, Request};
|
|
|
|
|
2022-05-09 16:17:27 +02:00
|
|
|
pub mod public;
|
2022-05-15 10:30:15 +02:00
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub enum NetRes<S> {
|
|
|
|
Success(S),
|
|
|
|
Error(model::api::Failure),
|
|
|
|
Http(FetchError),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<S> FromResidual<Result<Infallible, NetRes<S>>> for NetRes<S> {
|
|
|
|
fn from_residual(residual: Result<Infallible, NetRes<S>>) -> Self {
|
|
|
|
match residual {
|
|
|
|
Ok(_s) => unreachable!(),
|
|
|
|
Err(s) => s,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn perform<S: serde::de::DeserializeOwned + 'static>(req: Request<'_>) -> NetRes<S> {
|
|
|
|
let res = match req.fetch().await {
|
|
|
|
Ok(res) => res,
|
|
|
|
Err(err) => return NetRes::Http(err),
|
|
|
|
};
|
|
|
|
if res.status().is_error() {
|
|
|
|
NetRes::Error(match res.json().await {
|
|
|
|
Ok(json) => json,
|
|
|
|
Err(_err) => match res.text().await {
|
|
|
|
Ok(text) => model::api::Failure { errors: vec![text] },
|
|
|
|
Err(err) => model::api::Failure {
|
|
|
|
errors: vec![format!("{:?}", err)],
|
|
|
|
},
|
|
|
|
},
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
match res.json().await {
|
|
|
|
Ok(json) => NetRes::Success(json),
|
|
|
|
Err(err) => NetRes::Http(err),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|