como/crates/como_api/src/router.rs

74 lines
2.2 KiB
Rust
Raw Normal View History

use std::env;
2022-10-04 11:06:48 +02:00
use anyhow::Context;
use axum::extract::FromRef;
use axum::http::{HeaderValue, Method};
use axum::Router;
2022-10-04 11:06:48 +02:00
use como_infrastructure::register::ServiceRegister;
use tower::ServiceBuilder;
use tower_http::{cors::CorsLayer, trace::TraceLayer};
use crate::controllers::auth::AuthController;
2022-10-04 11:06:48 +02:00
use crate::controllers::graphql::GraphQLController;
2022-10-04 11:06:48 +02:00
pub struct Api;
impl Api {
pub async fn new(
port: u32,
cors_origin: &str,
service_register: ServiceRegister,
) -> anyhow::Result<()> {
let app_state = AppState {
service_register: service_register.clone(),
};
2022-10-04 11:06:48 +02:00
let router = Router::new()
.nest(
"/auth",
AuthController::new_router(service_register.clone(), app_state.clone()).await?,
)
2022-10-04 11:06:48 +02:00
.nest(
"/graphql",
GraphQLController::new_router(service_register.clone(), app_state.clone()),
2022-10-04 11:06:48 +02:00
)
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(
CorsLayer::new()
.allow_origin(
cors_origin
.parse::<HeaderValue>()
.context("could not parse cors origin as header")?,
)
.allow_headers([axum::http::header::CONTENT_TYPE])
.allow_methods([Method::GET, Method::POST, Method::OPTIONS])
.allow_credentials(true),
),
2022-10-04 11:06:48 +02:00
);
let host = env::var("HOST").unwrap_or("0.0.0.0".to_string());
tracing::info!("running on: {host}:{}", port);
axum::Server::bind(&format!("{host}:{}", port).parse().unwrap())
2022-10-04 11:06:48 +02:00
.serve(router.into_make_service())
.await
.context("error while starting API")?;
Ok(())
}
}
#[derive(Clone)]
pub struct AppState {
service_register: ServiceRegister,
}
impl FromRef<AppState> for ServiceRegister {
fn from_ref(input: &AppState) -> Self {
input.service_register.clone()
}
}