/
main.rs
125 lines (110 loc) · 3.12 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
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
use actix_cors::Cors;
use actix_web::{guard, web, App, HttpResponse, HttpServer, Result};
use async_graphql::http::playground_source;
use async_graphql::{Deferred, EmptyMutation, EmptySubscription, Object, Schema};
use async_graphql_actix_web::{GQLRequest, GQLResponseStream};
use std::time::Duration;
type DeferSchema = Schema<Query, EmptyMutation, EmptySubscription>;
struct Comment {
user: String,
text: String,
}
#[Object]
impl Comment {
async fn user(&self) -> &str {
actix_rt::time::delay_for(Duration::from_secs(2)).await;
&self.user
}
async fn text(&self) -> &str {
&self.text
}
}
struct Book {
id: i32,
title: String,
author: String,
}
#[Object]
impl Book {
async fn title(&self) -> &str {
&self.title
}
async fn author(&self) -> &str {
&self.author
}
async fn comments(&self) -> Deferred<Vec<Comment>> {
if self.id == 1 {
vec![
Comment {
user: "John".to_string(),
text: "I liked it".to_string(),
},
Comment {
user: "Mary".to_string(),
text: "It is a book".to_string(),
},
]
.into()
} else if self.id == 2 {
vec![
Comment {
user: "Alberta".to_string(),
text: "Amazing :-)".to_string(),
},
Comment {
user: "Joanna".to_string(),
text: "Excellent".to_string(),
},
]
.into()
} else {
Vec::new().into()
}
}
}
struct Query;
#[Object]
impl Query {
async fn books(&self) -> Vec<Book> {
vec![
Book {
id: 1,
title: "Harry Potter and the Chamber of Secrets".to_string(),
author: "J.K. Rowling".to_string(),
},
Book {
id: 2,
title: "Jurassic Park".to_string(),
author: "Michael Crichton".to_string(),
},
Book {
id: 3,
title: "Moby Dick".to_string(),
author: "Herman Melville".to_string(),
},
]
}
}
async fn index(schema: web::Data<DeferSchema>, req: GQLRequest) -> GQLResponseStream {
req.into_inner().execute_stream(&schema).await.into()
}
async fn index_playground() -> Result<HttpResponse> {
Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(playground_source("/", Some("/"))))
}
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
let schema = Schema::new(Query, EmptyMutation, EmptySubscription);
println!("Playground: http://localhost:8000");
HttpServer::new(move || {
App::new()
.wrap(Cors::default())
.data(schema.clone())
.service(web::resource("/").guard(guard::Post()).to(index))
.service(web::resource("/").guard(guard::Get()).to(index_playground))
})
.bind("127.0.0.1:8000")?
.run()
.await
}