/
simple.rs
68 lines (61 loc) · 1.95 KB
/
simple.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use juniper::{
tests::fixtures::starwars::schema::{Database, Query},
EmptyMutation, EmptySubscription, RootNode,
};
use rocket::{response::content::RawHtml, routes, State};
type Schema = RootNode<'static, Query, EmptyMutation<Database>, EmptySubscription<Database>>;
#[rocket::get("/")]
async fn homepage() -> RawHtml<&'static str> {
RawHtml(
"<html><h1>juniper_rocket/simple example</h1>\
<div>visit <a href=\"/graphiql\">GraphiQL</a></div>\
<div>visit <a href=\"/playground\">GraphQL Playground</a></div>\
</html>",
)
}
#[rocket::get("/graphiql")]
fn graphiql() -> RawHtml<String> {
juniper_rocket::graphiql_source("/graphql", None)
}
#[rocket::get("/playground")]
fn playground() -> RawHtml<String> {
juniper_rocket::playground_source("/graphql", None)
}
// GET request accepts query parameters like these:
// ?query=<urlencoded-graphql-query-string>
// &operationName=<optional-name>
// &variables=<optional-json-encoded-variables>
// See details here: https://graphql.org/learn/serving-over-http#get-request
#[rocket::get("/graphql?<request..>")]
async fn get_graphql(
db: &State<Database>,
request: juniper_rocket::GraphQLRequest,
schema: &State<Schema>,
) -> juniper_rocket::GraphQLResponse {
request.execute(schema, db).await
}
#[rocket::post("/graphql", data = "<request>")]
async fn post_graphql(
db: &State<Database>,
request: juniper_rocket::GraphQLRequest,
schema: &State<Schema>,
) -> juniper_rocket::GraphQLResponse {
request.execute(schema, db).await
}
#[rocket::main]
async fn main() {
_ = rocket::build()
.manage(Database::new())
.manage(Schema::new(
Query,
EmptyMutation::new(),
EmptySubscription::new(),
))
.mount(
"/",
routes![homepage, graphiql, playground, get_graphql, post_graphql],
)
.launch()
.await
.expect("server to launch");
}