bazzar/crates/web/src/api.rs

54 lines
1.4 KiB
Rust
Raw Normal View History

2022-05-15 10:30:15 +02:00
use std::convert::Infallible;
use std::ops::FromResidual;
2023-05-25 15:56:15 +02:00
// use seed::{FetchError, Request};
2022-05-15 10:30:15 +02:00
2022-05-17 08:23:39 +02:00
pub mod admin;
2022-05-09 16:17:27 +02:00
pub mod public;
2022-05-15 10:30:15 +02:00
2022-05-28 14:03:14 +02:00
#[must_use]
2022-05-15 10:30:15 +02:00
#[derive(Debug)]
pub enum NetRes<S> {
Success(S),
Error(model::api::Failure),
Http(FetchError),
}
2022-05-17 08:23:39 +02:00
impl<S> From<FetchError> for NetRes<S> {
fn from(e: FetchError) -> Self {
Self::Http(e)
}
}
2022-05-15 10:30:15 +02:00
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] },
2022-05-15 11:38:35 +02:00
Err(_err) => model::api::Failure {
errors: vec!["There was internal server error. Please try later".into()],
2022-05-15 10:30:15 +02:00
},
},
})
} else {
match res.json().await {
Ok(json) => NetRes::Success(json),
Err(err) => NetRes::Http(err),
}
}
}