-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathwundergraph_example.rs
139 lines (124 loc) · 4.28 KB
/
wundergraph_example.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
#![deny(missing_debug_implementations, missing_copy_implementations)]
#![warn(
clippy::print_stdout,
clippy::wrong_pub_self_convention,
clippy::mut_mut,
clippy::non_ascii_literal,
clippy::similar_names,
clippy::unicode_not_nfc,
clippy::enum_glob_use,
clippy::if_not_else,
clippy::items_after_statements,
clippy::used_underscore_binding,
clippy::cargo_common_metadata,
clippy::dbg_macro,
clippy::doc_markdown,
clippy::filter_map,
clippy::map_flatten,
clippy::match_same_arms,
clippy::needless_borrow,
clippy::option_map_unwrap_or,
clippy::option_map_unwrap_or_else,
clippy::redundant_clone,
clippy::result_map_unwrap_or_else,
clippy::unnecessary_unwrap,
clippy::unseparated_literal_suffix,
clippy::wildcard_dependencies
)]
use actix_web::web::{Data, Json};
use actix_web::{middleware, web, App, HttpResponse, HttpServer};
use diesel::r2d2::{ConnectionManager, Pool};
use juniper::graphiql::graphiql_source;
use juniper::http::GraphQLRequest;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::sync::Arc;
use structopt::StructOpt;
use wundergraph::scalar::WundergraphScalarValue;
use wundergraph_example::mutations::Mutation;
use wundergraph_example::*;
#[derive(Debug, StructOpt)]
#[structopt(name = "wundergraph_example")]
struct Opt {
#[structopt(short = "u", long = "db-url")]
database_url: String,
#[structopt(short = "s", long = "socket", default_value = "127.0.0.1:8000")]
socket: String,
}
// actix integration stuff
#[derive(Serialize, Deserialize, Debug)]
pub struct GraphQLData(GraphQLRequest<WundergraphScalarValue>);
#[derive(Clone)]
struct AppState {
schema: Arc<Schema<MyContext<DBConnection>>>,
pool: Arc<Pool<ConnectionManager<DBConnection>>>,
}
fn graphiql() -> HttpResponse {
let html = graphiql_source("/graphql");
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(html)
}
fn graphql(
Json(GraphQLData(data)): Json<GraphQLData>,
st: Data<AppState>,
) -> Result<HttpResponse, failure::Error> {
let ctx = MyContext::new(st.get_ref().pool.get()?);
let res = data.execute(&st.get_ref().schema, &ctx);
Ok(HttpResponse::Ok()
.content_type("application/json")
.body(serde_json::to_string(&res)?))
}
fn run_migrations(conn: &DBConnection) {
let mut migration_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
migration_path.push("migrations");
if cfg!(feature = "postgres") {
migration_path.push("pg");
} else if cfg!(feature = "sqlite") {
migration_path.push("sqlite");
}
let pending_migrations =
::diesel_migrations::mark_migrations_in_directory(conn, &migration_path)
.unwrap()
.into_iter()
.filter_map(|(migration, run)| if run { None } else { Some(migration) });
::diesel_migrations::run_migrations(conn, pending_migrations, &mut ::std::io::stdout())
.expect("Failed to run migrations");
}
#[allow(clippy::print_stdout)]
fn main() {
let opt = Opt::from_args();
::std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
let manager = ConnectionManager::<DBConnection>::new(opt.database_url);
let pool = Pool::builder()
.max_size(1)
.build(manager)
.expect("Failed to init pool");
run_migrations(&pool.get().expect("Failed to get db connection"));
let query = Query::<MyContext<DBConnection>>::default();
let mutation = Mutation::<MyContext<DBConnection>>::default();
let schema = Schema::new(query, mutation);
let schema = Arc::new(schema);
let pool = Arc::new(pool);
let data = AppState { schema, pool };
let url = opt.socket;
println!("Started http server: http://{}", url);
HttpServer::new(move || {
App::new()
.data(data.clone())
.wrap(middleware::Logger::default())
.route("/graphql", web::get().to(graphql))
.route("/graphql", web::post().to(graphql))
.route("/graphiql", web::get().to(graphiql))
.default_service(web::route().to(|| {
HttpResponse::Found()
.header("location", "/graphiql")
.finish()
}))
})
.bind(&url)
.expect("Failed to start server")
.run()
.unwrap();
}