1
0
mirror of https://github.com/actix/examples synced 2024-11-24 06:43:00 +01:00
examples/graphql/async-graphql/src/main.rs

51 lines
1.5 KiB
Rust
Raw Normal View History

2022-02-17 22:29:55 +01:00
use actix_cors::Cors;
use actix_web::{get, middleware::Logger, route, web, App, HttpServer, Responder};
use actix_web_lab::respond::Html;
use async_graphql::{
http::{playground_source, GraphQLPlaygroundConfig},
EmptyMutation, EmptySubscription, Schema,
};
use async_graphql_actix_web::{GraphQLRequest, GraphQLResponse};
mod star_wars;
use self::star_wars::{QueryRoot, StarWars, StarWarsSchema};
/// GraphQL endpoint
#[route("/graphql", method = "GET", method = "POST")]
2022-02-18 03:44:02 +01:00
async fn graphql(schema: web::Data<StarWarsSchema>, req: GraphQLRequest) -> GraphQLResponse {
2022-02-17 22:29:55 +01:00
schema.execute(req.into_inner()).await.into()
}
/// GraphiQL playground UI
#[get("/graphiql")]
async fn graphql_playground() -> impl Responder {
Html(playground_source(
GraphQLPlaygroundConfig::new("/graphql").subscription_endpoint("/graphql"),
))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
.data(StarWars::new())
.finish();
log::info!("starting HTTP server on port 8080");
log::info!("GraphiQL playground: http://localhost:8080/graphiql");
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(schema.clone()))
.service(graphql)
.service(graphql_playground)
.wrap(Cors::permissive())
.wrap(Logger::default())
})
.workers(2)
.bind(("127.0.0.1", 8080))?
.run()
.await
}