diff --git a/examples/juniper/Cargo.toml b/examples/juniper/Cargo.toml index d66edc0c4..ffcd6616e 100644 --- a/examples/juniper/Cargo.toml +++ b/examples/juniper/Cargo.toml @@ -15,3 +15,4 @@ serde_json = "1.0" serde_derive = "1.0" juniper = "0.9.2" +lazy_static = "1.0" diff --git a/examples/juniper/src/main.rs b/examples/juniper/src/main.rs index b5c620f1b..ba9c6bf00 100644 --- a/examples/juniper/src/main.rs +++ b/examples/juniper/src/main.rs @@ -1,15 +1,20 @@ //! Actix web juniper example //! -//! Juniper is a graphql framework implemetation for rust +//! A simple example integrating juniper in actix-web extern crate serde; extern crate serde_json; #[macro_use] +extern crate serde_derive; +#[macro_use] +extern crate lazy_static; +#[macro_use] extern crate juniper; extern crate futures; extern crate actix; extern crate actix_web; extern crate env_logger; +use actix::*; use actix_web::*; use juniper::http::graphiql::graphiql_source; use juniper::http::GraphQLRequest; @@ -21,8 +26,35 @@ mod schema; use schema::Schema; use schema::create_schema; +lazy_static! { + static ref SCHEMA: Schema = create_schema(); +} + struct State { - schema: Schema, + executor: Addr, +} + +#[derive(Serialize, Deserialize)] +pub struct GraphQLData(GraphQLRequest); + +impl Message for GraphQLData { + type Result = Result; +} + +pub struct GraphQLExecutor; + +impl Actor for GraphQLExecutor { + type Context = SyncContext; +} + +impl Handler for GraphQLExecutor { + type Result = Result; + + fn handle(&mut self, msg: GraphQLData, _: &mut Self::Context) -> Self::Result { + let res = msg.0.execute(&SCHEMA, &()); + let res_text = serde_json::to_string(&res)?; + Ok(res_text) + } } fn graphiql(_req: HttpRequest) -> Result { @@ -33,11 +65,18 @@ fn graphiql(_req: HttpRequest) -> Result { } fn graphql(req: HttpRequest) -> Box> { + req.json() .from_err() - .and_then(move |val: GraphQLRequest| { - let response = val.execute(&req.state().schema, &()); - Ok(httpcodes::HTTPOk.build().json(response)?) + .and_then(move |val: GraphQLData| { + req.state().executor.send(val) + .from_err() + .and_then(|res| { + match res { + Ok(user) => Ok(httpcodes::HTTPOk.build().body(user)?), + Err(_) => Ok(httpcodes::HTTPInternalServerError.into()) + } + }) }) .responder() } @@ -47,9 +86,13 @@ fn main() { let _ = env_logger::init(); let sys = actix::System::new("juniper-example"); + let addr = SyncArbiter::start(3, || { + GraphQLExecutor{} + }); + // Start http server let _addr = HttpServer::new(move || { - Application::with_state(State{schema: create_schema() }) + Application::with_state(State{executor: addr.clone()}) // enable logger .middleware(middleware::Logger::default()) .resource("/graphql", |r| r.method(Method::POST).a(graphql))