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