|
| 1 | +#![deny(warnings)] |
| 2 | + |
| 3 | +extern crate log; |
| 4 | +use actix_cors::Cors; |
| 5 | +use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer}; |
| 6 | +use juniper::{ |
| 7 | + tests::{model::Database, schema::Query}, |
| 8 | + EmptyMutation, EmptySubscription, RootNode, |
| 9 | +}; |
| 10 | +use juniper_actix::{ |
| 11 | + graphiql_handler as gqli_handler, graphql_handler, playground_handler as play_handler, |
| 12 | +}; |
| 13 | + |
| 14 | +type Schema = RootNode<'static, Query, EmptyMutation<Database>, EmptySubscription<Database>>; |
| 15 | + |
| 16 | +fn schema() -> Schema { |
| 17 | + Schema::new( |
| 18 | + Query, |
| 19 | + EmptyMutation::<Database>::new(), |
| 20 | + EmptySubscription::<Database>::new(), |
| 21 | + ) |
| 22 | +} |
| 23 | + |
| 24 | +async fn graphiql_handler() -> Result<HttpResponse, Error> { |
| 25 | + gqli_handler("/", None).await |
| 26 | +} |
| 27 | +async fn playground_handler() -> Result<HttpResponse, Error> { |
| 28 | + play_handler("/", None).await |
| 29 | +} |
| 30 | +async fn graphql( |
| 31 | + req: actix_web::HttpRequest, |
| 32 | + payload: actix_web::web::Payload, |
| 33 | + schema: web::Data<Schema>, |
| 34 | +) -> Result<HttpResponse, Error> { |
| 35 | + let context = Database::new(); |
| 36 | + graphql_handler(&schema, &context, req, payload).await |
| 37 | +} |
| 38 | + |
| 39 | +#[actix_rt::main] |
| 40 | +async fn main() -> std::io::Result<()> { |
| 41 | + ::std::env::set_var("RUST_LOG", "actix_web=info"); |
| 42 | + env_logger::init(); |
| 43 | + let server = HttpServer::new(move || { |
| 44 | + App::new() |
| 45 | + .data(schema()) |
| 46 | + .wrap(middleware::Compress::default()) |
| 47 | + .wrap(middleware::Logger::default()) |
| 48 | + .wrap( |
| 49 | + Cors::new() |
| 50 | + .allowed_methods(vec!["POST", "GET"]) |
| 51 | + .supports_credentials() |
| 52 | + .max_age(3600) |
| 53 | + .finish(), |
| 54 | + ) |
| 55 | + .service( |
| 56 | + web::resource("/") |
| 57 | + .route(web::post().to(graphql)) |
| 58 | + .route(web::get().to(graphql)), |
| 59 | + ) |
| 60 | + .service(web::resource("/playground").route(web::get().to(playground_handler))) |
| 61 | + .service(web::resource("/graphiql").route(web::get().to(graphiql_handler))) |
| 62 | + }); |
| 63 | + server.bind("127.0.0.1:8080").unwrap().run().await |
| 64 | +} |
0 commit comments