Files
axum/examples/async-graphql/src/main.rs
T

34 lines
1.1 KiB
Rust
Raw Normal View History

2021-08-04 18:10:20 +08:00
mod starwars;
use async_graphql::http::{playground_source, GraphQLPlaygroundConfig};
use async_graphql::{EmptyMutation, EmptySubscription, Request, Response, Schema};
use axum::response::IntoResponse;
use axum::{extract::Extension, response::Html, routing::get, AddExtensionLayer, Json, Router};
2021-08-04 18:10:20 +08:00
use starwars::{QueryRoot, StarWars, StarWarsSchema};
2021-08-18 00:04:15 +02:00
async fn graphql_handler(schema: Extension<StarWarsSchema>, req: Json<Request>) -> Json<Response> {
2021-08-04 18:10:20 +08:00
schema.execute(req.0).await.into()
}
async fn graphql_playground() -> impl IntoResponse {
2021-08-18 00:04:15 +02:00
Html(playground_source(GraphQLPlaygroundConfig::new("/")))
2021-08-04 18:10:20 +08:00
}
#[tokio::main]
async fn main() {
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
.data(StarWars::new())
.finish();
let app = Router::new()
.route("/", get(graphql_playground).post(graphql_handler))
2021-08-04 18:10:20 +08:00
.layer(AddExtensionLayer::new(schema));
println!("Playground: http://localhost:3000");
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
2021-08-04 18:10:20 +08:00
.serve(app.into_make_service())
.await
.unwrap();
}