2018-04-13 09:18:42 +08:00
|
|
|
//! Actix web juniper example
|
|
|
|
//!
|
|
|
|
//! A simple example integrating juniper in actix-web
|
2019-03-10 19:19:50 -07:00
|
|
|
use std::io;
|
|
|
|
use std::sync::Arc;
|
|
|
|
|
|
|
|
use actix_web::{middleware, web, App, Error, HttpResponse, HttpServer};
|
2018-04-13 09:18:42 +08:00
|
|
|
use juniper::http::graphiql::graphiql_source;
|
|
|
|
use juniper::http::GraphQLRequest;
|
|
|
|
|
|
|
|
mod schema;
|
|
|
|
|
2019-03-10 19:19:50 -07:00
|
|
|
use crate::schema::{create_schema, Schema};
|
2018-04-13 09:18:42 +08:00
|
|
|
|
2019-12-08 00:03:53 +06:00
|
|
|
async fn graphiql() -> HttpResponse {
|
|
|
|
let html = graphiql_source("http://127.0.0.1:8080/graphql");
|
|
|
|
HttpResponse::Ok()
|
|
|
|
.content_type("text/html; charset=utf-8")
|
|
|
|
.body(html)
|
2018-04-13 09:18:42 +08:00
|
|
|
}
|
|
|
|
|
2019-12-08 00:03:53 +06:00
|
|
|
async fn graphql(
|
|
|
|
st: web::Data<Arc<Schema>>,
|
|
|
|
data: web::Json<GraphQLRequest>,
|
2019-12-07 18:59:35 +01:00
|
|
|
) -> Result<HttpResponse, Error> {
|
2019-12-08 00:03:53 +06:00
|
|
|
let user = web::block(move || {
|
|
|
|
let res = data.execute(&st, &());
|
|
|
|
Ok::<_, serde_json::error::Error>(serde_json::to_string(&res)?)
|
|
|
|
})
|
|
|
|
.await?;
|
|
|
|
Ok(HttpResponse::Ok()
|
|
|
|
.content_type("application/json")
|
|
|
|
.body(user))
|
2018-04-13 09:18:42 +08:00
|
|
|
}
|
|
|
|
|
2019-12-08 00:03:53 +06:00
|
|
|
#[actix_rt::main]
|
|
|
|
async fn main() -> io::Result<()> {
|
|
|
|
std::env::set_var("RUST_LOG", "actix_web=info");
|
|
|
|
env_logger::init();
|
|
|
|
|
|
|
|
// Create Juniper schema
|
|
|
|
let schema = std::sync::Arc::new(create_schema());
|
|
|
|
|
|
|
|
// Start http server
|
|
|
|
HttpServer::new(move || {
|
|
|
|
App::new()
|
|
|
|
.data(schema.clone())
|
|
|
|
.wrap(middleware::Logger::default())
|
|
|
|
.service(web::resource("/graphql").route(web::post().to(graphql)))
|
|
|
|
.service(web::resource("/graphiql").route(web::get().to(graphiql)))
|
|
|
|
})
|
|
|
|
.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
|
|
|
}
|