lxy 0.1.1

A convenient async http and RPC framework in Rust
Documentation
use std::{
  future::Future,
  pin::Pin,
  task::{Context, Poll},
};

use axum::body::Body;
use http::Request;
use tower::Service;

use crate::app::{context::run_with_app, layer::AppService};

type HttpRequest = Request<Body>;

impl<S> Service<HttpRequest> for AppService<S>
where
  S: Service<HttpRequest> + Clone + Send + 'static,
  S::Future: Send,
{
  type Response = S::Response;
  type Error = S::Error;
  type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

  fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
    self.inner.poll_ready(cx)
  }

  fn call(&mut self, req: HttpRequest) -> Self::Future {
    let inner = self.inner.clone();
    let mut inner = std::mem::replace(&mut self.inner, inner);
    let app = self.app.clone();

    Box::pin(async move { run_with_app(app, inner.call(req)).await })
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::{
    app::{App, get_app, layer::AppLayer},
    container::Container,
    http::routing::Router,
  };

  #[tokio::test]
  async fn test_http_app_layer() {
    #[derive(Clone)]
    struct TestService {
      value: i32,
    }

    async fn handler() -> Result<String, crate::error::Error> {
      let app = get_app()?;
      let service = app.get::<TestService>().unwrap();
      Ok(service.value.to_string())
    }

    let mut app = App::new();
    app.container.bind(TestService { value: 42 });

    let router = Router::compose(|router| {
      router.middleware(AppLayer(app.clone())).get("/", handler);
    });

    let req = Request::builder().uri("/").body(Body::empty()).unwrap();

    let response = router.build().call(req).await.unwrap();
    let body = axum::body::to_bytes(response.into_body(), usize::MAX)
      .await
      .unwrap();

    assert_eq!(&body[..], b"42");
  }
}