-
Notifications
You must be signed in to change notification settings - Fork 54
/
main.rs
94 lines (69 loc) · 2.52 KB
/
main.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
use std::env;
use async_graphql::{http::GraphiQLSource, EmptyMutation, EmptySubscription, Schema};
use async_std::task;
use starwars::{QueryRoot, StarWars};
use tide::{http::mime, Body, Response, StatusCode};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
fn main() -> Result<()> {
task::block_on(run())
}
async fn run() -> Result<()> {
let listen_addr = env::var("LISTEN_ADDR").unwrap_or_else(|_| "localhost:8000".to_owned());
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
.data(StarWars::new())
.finish();
println!("GraphiQL IDE: http://{}", listen_addr);
let mut app = tide::new();
app.at("/graphql").post(async_graphql_tide::graphql(schema));
app.at("/").get(|_| async move {
let mut resp = Response::new(StatusCode::Ok);
resp.set_body(Body::from_string(
GraphiQLSource::build().endpoint("/graphql").finish(),
));
resp.set_content_type(mime::HTML);
Ok(resp)
});
app.listen(listen_addr).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use async_std::prelude::*;
use serde_json::json;
use super::*;
#[test]
fn sample() -> Result<()> {
task::block_on(async {
let listen_addr = find_listen_addr().await;
env::set_var("LISTEN_ADDR", format!("{}", listen_addr));
let server: task::JoinHandle<Result<()>> = task::spawn(async move {
run().await?;
Ok(())
});
let client: task::JoinHandle<Result<()>> = task::spawn(async move {
let listen_addr = env::var("LISTEN_ADDR").unwrap();
task::sleep(Duration::from_millis(300)).await;
let string = surf::post(format!("http://{}/graphql", listen_addr))
.body(Body::from(r#"{"query":"{ human(id:\"1000\") {name} }"}"#))
.header("Content-Type", "application/json")
.recv_string()
.await?;
assert_eq!(
string,
json!({"data":{"human":{"name":"Luke Skywalker"}}}).to_string()
);
Ok(())
});
server.race(client).await?;
Ok(())
})
}
async fn find_listen_addr() -> async_std::net::SocketAddr {
async_std::net::TcpListener::bind("localhost:0")
.await
.unwrap()
.local_addr()
.unwrap()
}
}