como/crates/como_api/src/controllers/graphql.rs
kjuulh 6e16fc6b2b
feat: move project to crates
Signed-off-by: kjuulh <contact@kjuulh.io>
2023-10-21 11:14:58 +02:00

49 lines
1.5 KiB
Rust

use super::auth::UserFromSession;
use crate::router::AppState;
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
use async_graphql::{EmptySubscription, Schema};
use async_graphql_axum::{GraphQLRequest, GraphQLResponse};
use axum::response::Html;
use axum::{http::StatusCode, response::IntoResponse, routing::get, Extension, Router};
use como_domain::user::ContextUserExt;
use como_domain::Context;
use como_gql::graphql::{ComoSchema, MutationRoot, QueryRoot};
use como_infrastructure::register::ServiceRegister;
use tower::ServiceBuilder;
pub struct GraphQLController;
impl GraphQLController {
pub fn new_router(service_register: ServiceRegister, state: AppState) -> Router {
let schema = Schema::build(QueryRoot, MutationRoot, EmptySubscription)
.data(service_register)
.finish();
Router::new()
.route("/", get(graphql_playground).post(graphql_handler))
.layer(ServiceBuilder::new().layer(Extension(schema)))
.with_state(state)
}
}
pub async fn graphql_handler(
user: UserFromSession,
schema: Extension<ComoSchema>,
req: GraphQLRequest,
) -> Result<GraphQLResponse, StatusCode> {
let req = req.into_inner();
let req = req.data(user.user.clone());
let context = Context::new();
let context = context.set_user_id(user.user.id.clone());
let req = req.data(context);
Ok(schema.execute(req).await.into())
}
pub async fn graphql_playground() -> impl IntoResponse {
Html(playground_source(GraphQLPlaygroundConfig::new("/graphql")))
}