como/como_api/src/controllers/graphql.rs

49 lines
1.4 KiB
Rust
Raw Normal View History

use super::auth::UserFromSession;
use crate::{router::AppState};
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
2022-10-04 12:06:00 +02:00
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,
2022-10-04 12:06:00 +02:00
};
use como_gql::graphql::{ComoSchema, MutationRoot, QueryRoot};
2022-10-04 11:06:48 +02:00
use como_infrastructure::register::ServiceRegister;
use tower::ServiceBuilder;
2022-10-04 11:06:48 +02:00
pub struct GraphQLController;
impl GraphQLController {
pub fn new_router(service_register: ServiceRegister, state: AppState) -> Router {
2022-10-04 12:06:00 +02:00
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)
2022-10-04 11:06:48 +02:00
}
}
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);
Ok(schema.execute(req).await.into())
}
pub async fn graphql_playground() -> impl IntoResponse {
Html(playground_source(GraphQLPlaygroundConfig::new("/graphql")))
}