Skip to content

Instantly share code, notes, and snippets.

@tcr
Created May 3, 2018 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcr/a53f9e067268fb06fc44b498bb44db53 to your computer and use it in GitHub Desktop.
Save tcr/a53f9e067268fb06fc44b498bb44db53 to your computer and use it in GitHub Desktop.
rouille_with_juniper.rs
#!/usr/bin/env run-cargo-script
//! ```cargo
//! [dependencies]
//! juniper = "*"
//! rouille = "*"
//! serde_json = "*"
//! serde = "*"
//! ```
#[macro_use] extern crate rouille;
#[macro_use] extern crate juniper;
extern crate serde_json;
use juniper::http::{GraphQLRequest};
use juniper::{FieldResult, EmptyMutation};
struct Query;
graphql_object!(Query: Ctx |&self| {
field hello(&executor) -> FieldResult<String> {
// Use the special &executor argument to fetch the response string
Ok(executor.context().0.clone())
}
});
// Arbitrary context data.
struct Ctx(String);
// A root schema consists of a query and a mutation.
// Request queries can be executed against a RootNode.
type Schema = juniper::RootNode<'static, Query, EmptyMutation<Ctx>>;
fn main() {
eprintln!("http://0.0.0.0:12000");
rouille::start_server("0.0.0.0:12000", move |request| {
router!(request,
(GET) (/) => {
// Builds a `Response` object that contains the "hello world" text.
rouille::Response::html(r#"
<h1>hello world</h1>
<form action="/graphql" method="post">
<input type="text" name="query" value="query { hello }">
<button type="submit">Submit</button>
</form>
"#)
},
(POST) (/graphql) => {
let data = try_or_400!(post_input!(request, {
query: String,
}));
// Create a context object.
let ctx = Ctx("world!".to_string());
// Populate the GraphQL request object.
let req = GraphQLRequest::new(
data.query,
None,
None,
);
// Run the executor.
let res = req.execute(
&Schema::new(Query, EmptyMutation::new()),
&ctx,
);
rouille::Response::json(&res)
},
_ => rouille::Response::empty_404()
)
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment