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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
use finchers::endpoint::with_get_cx;
use finchers::endpoint::{ApplyContext, ApplyResult, Endpoint};
use finchers::endpoints::body;
use finchers::error;
use finchers::error::Error;
use finchers::output::{Output, OutputContext};
use futures::{Future, Poll};
use juniper;
use juniper::{GraphQLType, InputValue, RootNode};
use failure::SyncFailure;
use http::Method;
use http::{header, Response, StatusCode};
use percent_encoding::percent_decode;
use serde_json;
use serde_qs;
pub fn graphql_request() -> GraphQLRequestEndpoint {
GraphQLRequestEndpoint { _priv: () }
}
#[allow(missing_docs)]
#[derive(Debug)]
pub struct GraphQLRequestEndpoint {
_priv: (),
}
impl<'a> Endpoint<'a> for GraphQLRequestEndpoint {
type Output = (GraphQLRequest,);
type Future = RequestFuture<'a>;
fn apply(&'a self, cx: &mut ApplyContext<'_>) -> ApplyResult<Self::Future> {
if cx.input().method() == Method::GET {
Ok(RequestFuture {
kind: RequestKind::Get,
})
} else {
Ok(RequestFuture {
kind: RequestKind::Post(body::receive_all().apply(cx)?),
})
}
}
}
#[doc(hidden)]
#[derive(Debug)]
pub struct RequestFuture<'a> {
kind: RequestKind<'a>,
}
#[derive(Debug)]
enum RequestKind<'a> {
Get,
Post(<body::ReceiveAll as Endpoint<'a>>::Future),
}
impl<'a> Future for RequestFuture<'a> {
type Item = (GraphQLRequest,);
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let result = match self.kind {
RequestKind::Get => with_get_cx(|input| {
let s = input
.uri()
.query()
.ok_or_else(|| error::bad_request("missing query string"))?;
parse_query_str(s)
}),
RequestKind::Post(ref mut f) => {
let (data,) = try_ready!(f.poll());
with_get_cx(
|input| match input.content_type().map_err(error::bad_request)? {
Some(m) if *m == "application/json" => {
serde_json::from_slice(&*data).map_err(error::bad_request)
}
Some(m) if *m == "application/graphql" => {
let query =
String::from_utf8(data.to_vec()).map_err(error::bad_request)?;
Ok(GraphQLRequest::single(query, None, None))
}
Some(_m) => Err(error::bad_request("unsupported content-type.")),
None => Err(error::bad_request("missing content-type.")),
},
)
}
};
result.map(|request| (request,).into())
}
}
#[derive(Debug, Deserialize)]
pub struct GraphQLRequest(GraphQLRequestKind);
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum GraphQLRequestKind {
Single(juniper::http::GraphQLRequest),
Batch(Vec<juniper::http::GraphQLRequest>),
}
impl GraphQLRequest {
fn single(
query: String,
operation_name: Option<String>,
variables: Option<InputValue>,
) -> GraphQLRequest {
GraphQLRequest(GraphQLRequestKind::Single(
juniper::http::GraphQLRequest::new(query, operation_name, variables),
))
}
pub fn execute<QueryT, MutationT, CtxT>(
&self,
root_node: &RootNode<'static, QueryT, MutationT>,
context: &CtxT,
) -> GraphQLResponse
where
QueryT: GraphQLType<Context = CtxT>,
MutationT: GraphQLType<Context = CtxT>,
{
use self::GraphQLRequestKind::*;
match self.0 {
Single(ref request) => {
let response = request.execute(root_node, context);
GraphQLResponse {
is_ok: response.is_ok(),
body: serde_json::to_vec(&response),
}
}
Batch(ref requests) => {
let responses: Vec<_> = requests
.iter()
.map(|request| request.execute(root_node, context))
.collect();
GraphQLResponse {
is_ok: responses.iter().all(|response| response.is_ok()),
body: serde_json::to_vec(&responses),
}
}
}
}
}
fn parse_query_str(s: &str) -> Result<GraphQLRequest, Error> {
#[derive(Debug, Deserialize)]
struct ParsedQuery {
query: String,
operation_name: Option<String>,
variables: Option<String>,
}
let parsed: ParsedQuery =
serde_qs::from_str(s).map_err(|e| error::fail(SyncFailure::new(e)))?;
let query = percent_decode(parsed.query.as_bytes())
.decode_utf8()
.map_err(error::bad_request)?
.into_owned();
let operation_name = match parsed.operation_name {
Some(s) => Some(
percent_decode(s.as_bytes())
.decode_utf8()
.map_err(error::bad_request)?
.into_owned(),
),
None => None,
};
let variables: Option<InputValue> = match parsed.variables {
Some(variables) => {
let decoded = percent_decode(variables.as_bytes())
.decode_utf8()
.map_err(error::bad_request)?;
serde_json::from_str(&*decoded)
.map(Some)
.map_err(error::bad_request)?
}
None => None,
};
Ok(GraphQLRequest::single(query, operation_name, variables))
}
#[derive(Debug)]
pub struct GraphQLResponse {
is_ok: bool,
body: Result<Vec<u8>, serde_json::Error>,
}
impl Output for GraphQLResponse {
type Body = Vec<u8>;
type Error = Error;
fn respond(self, _: &mut OutputContext<'_>) -> Result<Response<Self::Body>, Self::Error> {
let status = if self.is_ok {
StatusCode::OK
} else {
StatusCode::BAD_REQUEST
};
let body = self.body.map_err(error::fail)?;
Ok(Response::builder()
.status(status)
.header(header::CONTENT_TYPE, "application/json")
.body(body)
.expect("should be a valid response"))
}
}
#[cfg(test)]
mod tests {
use finchers::test;
use http::Request;
use super::{graphql_request, GraphQLRequest, GraphQLRequestKind};
#[test]
fn test_get_request() {
let mut runner = test::runner(graphql_request());
assert_matches!(
runner.apply(Request::get("/?query={{}}")),
Ok(GraphQLRequest(GraphQLRequestKind::Single(..)))
);
}
#[test]
fn test_json_request() {
let mut runner = test::runner(graphql_request());
assert_matches!(
runner.apply(
Request::post("/")
.header("content-type", "application/json")
.body(r#"{ "query": "{ apiVersion }" }"#),
),
Ok(GraphQLRequest(GraphQLRequestKind::Single(..)))
);
}
#[test]
fn test_batch_json_request() {
let mut runner = test::runner(graphql_request());
assert_matches!(
runner.apply(
Request::post("/")
.header("content-type", "application/json")
.body(
r#"[
{ "query": "{ apiVersion }" },
{ "query": "{ me { id } }" }
]"#,
),
),
Ok(GraphQLRequest(GraphQLRequestKind::Batch(..)))
);
}
#[test]
fn test_graphql_request() {
let mut runner = test::runner(graphql_request());
assert_matches!(
runner.apply(
Request::post("/")
.header("content-type", "application/graphql")
.body(r#"{ apiVersion }"#),
),
Ok(GraphQLRequest(GraphQLRequestKind::Single(..)))
);
}
}