2022-02-06 08:25:38 +00:00
|
|
|
//! Actix Web juniper example
|
2018-04-13 09:18:42 +08:00
|
|
|
//!
|
2022-02-06 08:13:24 +00:00
|
|
|
//! A simple example integrating juniper in Actix Web
|
2022-02-17 20:37:51 +00:00
|
|
|
|
|
|
|
use std::{io, sync::Arc};
|
2019-03-10 19:19:50 -07:00
|
|
|
|
2020-09-27 15:05:17 -05:00
|
|
|
use actix_cors::Cors;
|
2022-02-17 20:37:51 +00:00
|
|
|
use actix_web::{
|
|
|
|
get, middleware, route,
|
|
|
|
web::{self, Data},
|
|
|
|
App, HttpResponse, HttpServer, Responder,
|
|
|
|
};
|
|
|
|
use juniper::http::{graphiql::graphiql_source, GraphQLRequest};
|
2018-04-13 09:18:42 +08:00
|
|
|
|
|
|
|
mod schema;
|
|
|
|
|
2019-03-10 19:19:50 -07:00
|
|
|
use crate::schema::{create_schema, Schema};
|
2018-04-13 09:18:42 +08:00
|
|
|
|
2022-02-17 20:59:04 +00:00
|
|
|
/// GraphiQL playground UI
|
2022-02-17 20:37:51 +00:00
|
|
|
#[get("/graphiql")]
|
2022-02-17 20:59:04 +00:00
|
|
|
async fn graphql_playground() -> impl Responder {
|
2024-07-07 00:23:03 +01:00
|
|
|
web::Html::new(graphiql_source("/graphql", None))
|
2018-04-13 09:18:42 +08:00
|
|
|
}
|
|
|
|
|
2022-02-17 20:37:51 +00:00
|
|
|
/// GraphQL endpoint
|
|
|
|
#[route("/graphql", method = "GET", method = "POST")]
|
2022-02-18 02:44:02 +00:00
|
|
|
async fn graphql(st: web::Data<Schema>, data: web::Json<GraphQLRequest>) -> impl Responder {
|
2022-02-17 20:37:51 +00:00
|
|
|
let user = data.execute(&st, &()).await;
|
|
|
|
HttpResponse::Ok().json(user)
|
2018-04-13 09:18:42 +08:00
|
|
|
}
|
|
|
|
|
2020-09-12 16:49:45 +01:00
|
|
|
#[actix_web::main]
|
2019-12-08 00:03:53 +06:00
|
|
|
async fn main() -> io::Result<()> {
|
2022-02-17 20:37:51 +00:00
|
|
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
2019-12-08 00:03:53 +06:00
|
|
|
|
|
|
|
// Create Juniper schema
|
2022-02-17 20:37:51 +00:00
|
|
|
let schema = Arc::new(create_schema());
|
|
|
|
|
2022-02-17 21:29:55 +00:00
|
|
|
log::info!("starting HTTP server on port 8080");
|
|
|
|
log::info!("GraphiQL playground: http://localhost:8080/graphiql");
|
2019-12-08 00:03:53 +06:00
|
|
|
|
2022-02-17 20:37:51 +00:00
|
|
|
// Start HTTP server
|
2019-12-08 00:03:53 +06:00
|
|
|
HttpServer::new(move || {
|
|
|
|
App::new()
|
2022-02-17 20:37:51 +00:00
|
|
|
.app_data(Data::from(schema.clone()))
|
|
|
|
.service(graphql)
|
2022-02-17 20:59:04 +00:00
|
|
|
.service(graphql_playground)
|
2022-02-17 20:37:51 +00:00
|
|
|
// the graphiql UI requires CORS to be enabled
|
|
|
|
.wrap(Cors::permissive())
|
2019-12-08 00:03:53 +06:00
|
|
|
.wrap(middleware::Logger::default())
|
|
|
|
})
|
2022-02-17 20:37:51 +00:00
|
|
|
.workers(2)
|
2022-02-17 20:22:36 +00:00
|
|
|
.bind(("127.0.0.1", 8080))?
|
2019-12-25 20:48:33 +04:00
|
|
|
.run()
|
2019-12-08 00:03:53 +06:00
|
|
|
.await
|
2018-04-13 09:18:42 +08:00
|
|
|
}
|