async-graphql/examples/actix-web.rs

52 lines
1.7 KiB
Rust
Raw Normal View History

2020-03-05 13:34:31 +00:00
mod starwars;
2020-03-05 00:39:56 +00:00
use actix_web::{guard, web, App, HttpResponse, HttpServer};
2020-03-14 03:51:49 +00:00
use async_graphql::http::{graphiql_source, playground_source, GQLRequest, GQLResponse};
2020-03-19 09:20:12 +00:00
use async_graphql::{EmptyMutation, EmptySubscription, Schema};
2020-04-01 08:53:49 +00:00
use futures::TryFutureExt;
2020-03-05 00:39:56 +00:00
2020-03-19 09:20:12 +00:00
type StarWarsSchema = Schema<starwars::QueryRoot, EmptyMutation, EmptySubscription>;
2020-03-14 03:51:49 +00:00
async fn index(s: web::Data<StarWarsSchema>, req: web::Json<GQLRequest>) -> web::Json<GQLResponse> {
2020-04-01 08:53:49 +00:00
web::Json(GQLResponse(
2020-04-02 04:53:53 +00:00
futures::future::ready(req.into_inner().into_query_builder(&s))
2020-04-01 08:53:49 +00:00
.and_then(|builder| builder.execute())
.await,
))
2020-03-14 03:51:49 +00:00
}
2020-03-05 00:39:56 +00:00
async fn gql_playgound() -> HttpResponse {
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
2020-03-17 09:26:59 +00:00
.body(playground_source("/", None))
2020-03-05 00:39:56 +00:00
}
async fn gql_graphiql() -> HttpResponse {
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(graphiql_source("/"))
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
2020-03-05 13:34:31 +00:00
HttpServer::new(move || {
2020-03-05 00:39:56 +00:00
App::new()
2020-03-14 03:51:49 +00:00
.data(
2020-03-29 12:02:52 +00:00
Schema::build(starwars::QueryRoot, EmptyMutation, EmptySubscription)
2020-03-26 03:34:28 +00:00
.data(starwars::StarWars::new())
2020-03-29 12:02:52 +00:00
.extension(|| async_graphql::extensions::ApolloTracing::default())
.finish(),
2020-03-14 03:51:49 +00:00
)
.service(web::resource("/").guard(guard::Post()).to(index))
2020-03-05 00:39:56 +00:00
.service(web::resource("/").guard(guard::Get()).to(gql_playgound))
2020-03-05 06:23:55 +00:00
.service(
web::resource("/graphiql")
.guard(guard::Get())
.to(gql_graphiql),
)
2020-03-05 00:39:56 +00:00
})
.bind("127.0.0.1:8000")?
.run()
.await
}