Files
pixiv_downloader/src/server/traits.rs
2022-09-19 10:22:06 +00:00

42 lines
1.1 KiB
Rust

use super::context::ServerContext;
use crate::error::PixivDownloaderError;
use hyper::Body;
use hyper::Request;
use hyper::Response;
use json::JsonValue;
use std::sync::Arc;
pub trait MatchRoute<T, R> {
fn match_route(
&self,
ctx: &Arc<ServerContext>,
req: &Request<T>,
) -> Option<Box<dyn ResponseFor<T, R> + Send + Sync>>;
}
#[async_trait]
pub trait ResponseFor<T, R> {
async fn response(&self, req: Request<T>) -> Result<Response<R>, PixivDownloaderError>;
}
#[async_trait]
pub trait ResponseJsonFor<T> {
async fn response_json(
&self,
req: Request<T>,
) -> Result<Response<JsonValue>, PixivDownloaderError>;
}
#[async_trait]
impl<T, U> ResponseFor<T, Body> for U
where
U: ResponseJsonFor<T> + Sync + Send,
T: Sync + Send + 'static,
{
async fn response(&self, req: Request<T>) -> Result<Response<Body>, PixivDownloaderError> {
let re = self.response_json(req).await?;
let (parts, body) = re.into_parts();
Ok(Response::from_parts(parts, Body::from(body.to_string())))
}
}