-
Notifications
You must be signed in to change notification settings - Fork 417
/
subscription.rs
188 lines (166 loc) · 4.73 KB
/
subscription.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
//! This example demonstrates asynchronous subscriptions with [`warp`].
use std::{env, pin::Pin, sync::Arc, time::Duration};
use futures::Stream;
use juniper::{
graphql_object, graphql_subscription, graphql_value, EmptyMutation, FieldError, GraphQLEnum,
RootNode,
};
use juniper_graphql_ws::ConnectionConfig;
use warp::{http::Response, Filter};
#[derive(Clone)]
struct Context;
impl juniper::Context for Context {}
#[derive(Clone, Copy, GraphQLEnum)]
enum UserKind {
Admin,
User,
Guest,
}
struct User {
id: i32,
kind: UserKind,
name: String,
}
// Field resolvers implementation
#[graphql_object(context = Context)]
impl User {
fn id(&self) -> i32 {
self.id
}
fn kind(&self) -> UserKind {
self.kind
}
fn name(&self) -> &str {
&self.name
}
async fn friends(&self) -> Vec<User> {
if self.id == 1 {
vec![
User {
id: 11,
kind: UserKind::User,
name: "user11".into(),
},
User {
id: 12,
kind: UserKind::Admin,
name: "user12".into(),
},
User {
id: 13,
kind: UserKind::Guest,
name: "user13".into(),
},
]
} else if self.id == 2 {
vec![User {
id: 21,
kind: UserKind::User,
name: "user21".into(),
}]
} else if self.id == 3 {
vec![
User {
id: 31,
kind: UserKind::User,
name: "user31".into(),
},
User {
id: 32,
kind: UserKind::Guest,
name: "user32".into(),
},
]
} else {
vec![]
}
}
}
struct Query;
#[graphql_object(context = Context)]
impl Query {
async fn users(id: i32) -> Vec<User> {
vec![User {
id,
kind: UserKind::Admin,
name: "User Name".into(),
}]
}
}
type UsersStream = Pin<Box<dyn Stream<Item = Result<User, FieldError>> + Send>>;
struct Subscription;
#[graphql_subscription(context = Context)]
impl Subscription {
async fn users() -> UsersStream {
let mut interval = tokio::time::interval(Duration::from_secs(5));
let stream = async_stream::stream! {
let mut counter = 0;
loop {
counter += 1;
interval.tick().await;
if counter == 5 {
yield Err(FieldError::new(
"some field error from handler",
graphql_value!("some additional string"),
))
} else {
yield Ok(User {
id: counter,
kind: UserKind::Admin,
name: "stream user".into(),
})
}
}
};
Box::pin(stream)
}
}
type Schema = RootNode<'static, Query, EmptyMutation<Context>, Subscription>;
fn schema() -> Schema {
Schema::new(Query, EmptyMutation::new(), Subscription)
}
#[tokio::main]
async fn main() {
env::set_var("RUST_LOG", "subscription");
env_logger::init();
let log = warp::log("subscription");
let homepage = warp::path::end().map(|| {
Response::builder()
.header("content-type", "text/html")
.body(
"<html><h1>juniper_warp/subscription example</h1>\
<div>visit <a href=\"/graphiql\">GraphiQL</a></div>\
<div>visit <a href=\"/playground\">GraphQL Playground</a></div>\
</html>",
)
});
let schema = Arc::new(schema());
let routes = (warp::post()
.and(warp::path("graphql"))
.and(juniper_warp::make_graphql_filter(
schema.clone(),
warp::any().map(|| Context),
)))
.or(
warp::path("subscriptions").and(juniper_warp::subscriptions::make_ws_filter(
schema,
ConnectionConfig::new(Context),
)),
)
.or(warp::get()
.and(warp::path("playground"))
.and(juniper_warp::playground_filter(
"/graphql",
Some("/subscriptions"),
)))
.or(warp::get()
.and(warp::path("graphiql"))
.and(juniper_warp::graphiql_filter(
"/graphql",
Some("/subscriptions"),
)))
.or(homepage)
.with(log);
log::info!("Listening on 127.0.0.1:8080");
warp::serve(routes).run(([127, 0, 0, 1], 8080)).await;
}