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

48 lines
1.2 KiB
Rust
Raw Normal View History

2022-03-01 17:30:09 +08:00
//! Example async-graphql application.
//!
//! Run with
//!
//! ```not_rust
2022-04-29 18:53:41 +02:00
//! cd examples && cargo run -p example-async-graphql
2022-03-01 17:30:09 +08:00
//! ```
2021-08-04 18:10:20 +08:00
mod starwars;
use async_graphql::{
http::{playground_source, GraphQLPlaygroundConfig},
EmptyMutation, EmptySubscription, Request, Response, Schema,
};
use axum::{
extract::Extension,
response::{Html, IntoResponse},
routing::get,
2022-03-01 00:39:22 +01:00
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))
2022-03-01 00:39:22 +01:00
.layer(Extension(schema));
2021-08-04 18:10:20 +08:00
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();
}