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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
/*!

# juniper_iron

This repository contains the [Iron][Iron] web framework integration for
[Juniper][Juniper], a [GraphQL][GraphQL] implementation for Rust.

For documentation, including guides and examples, check out [Juniper][Juniper].

A basic usage example can also be found in the [Api documentation][documentation].

## Links

* [Juniper][Juniper]
* [Api Reference][documentation]
* [Iron framework][Iron]

## Integrating with Iron


For example, continuing from the schema created above and using Iron to expose
the schema on an HTTP endpoint supporting both GET and POST requests:

```rust,no_run
# use std::collections::HashMap;
#
use iron::prelude::*;
use juniper_iron::GraphQLHandler;
use juniper::{Context, EmptyMutation, EmptySubscription};
#
# use juniper::FieldResult;
#
# struct User { id: String, name: String, friend_ids: Vec<String>  }
# struct QueryRoot;
# struct Database { users: HashMap<String, User> }
#
# #[juniper::graphql_object(context = Database)]
# impl User {
#     fn id(&self) -> FieldResult<&String> {
#         Ok(&self.id)
#     }
#
#     fn name(&self) -> FieldResult<&String> {
#         Ok(&self.name)
#     }
#
#     fn friends(&self, context: &Database) -> FieldResult<Vec<&User>> {
#         Ok(self.friend_ids.iter()
#             .filter_map(|id| executor.context().users.get(id))
#             .collect())
#     }
# }
#
# #[juniper::graphql_object(context = Database, scalar = juniper::DefaultScalarValue)]
# impl QueryRoot {
#     fn user(context: &Database, id: String) -> FieldResult<Option<&User>> {
#         Ok(executor.context().users.get(&id))
#     }
# }

// This function is executed for every request. Here, we would realistically
// provide a database connection or similar. For this example, we'll be
// creating the database from scratch.
fn context_factory(_: &mut Request) -> IronResult<Database> {
    Ok(Database {
        users: vec![
            ( "1000".to_owned(), User {
                id: "1000".to_owned(), name: "Robin".to_owned(),
                friend_ids: vec!["1001".to_owned()] } ),
            ( "1001".to_owned(), User {
                id: "1001".to_owned(), name: "Max".to_owned(),
                friend_ids: vec!["1000".to_owned()] } ),
        ].into_iter().collect()
    })
}

impl Context for Database {}

fn main() {
    // GraphQLHandler takes a context factory function, the root object,
    // and the mutation object. If we don't have any mutations to expose, we
    // can use the empty tuple () to indicate absence.
    let graphql_endpoint = GraphQLHandler::new(
        context_factory,
        QueryRoot,
        EmptyMutation::<Database>::new(),
        EmptySubscription::<Database>::new(),
    );

    // Start serving the schema at the root on port 8080.
    Iron::new(graphql_endpoint).http("localhost:8080").unwrap();
}

```

See the the [`GraphQLHandler`][3] documentation for more information on what request methods are
supported.

[3]: ./struct.GraphQLHandler.html
[Iron]: https://github.com/iron/iron
[Juniper]: https://github.com/graphql-rust/juniper
[GraphQL]: http://graphql.org
[documentation]: https://docs.rs/juniper_iron

*/

#![doc(html_root_url = "https://docs.rs/juniper_iron/0.3.0")]

use std::{error::Error, fmt, io::Read, ops::Deref as _};

use iron::{
    headers::ContentType,
    itry, method,
    middleware::Handler,
    mime::{Mime, TopLevel},
    prelude::*,
    status,
};
use juniper::{
    http, http::GraphQLBatchRequest, DefaultScalarValue, GraphQLType, InputValue, RootNode,
    ScalarValue,
};
use serde_json::error::Error as SerdeError;
use urlencoded::{UrlDecodingError, UrlEncodedQuery};

/// Handler that executes `GraphQL` queries in the given schema
///
/// The handler responds to GET requests and POST requests only. In GET
/// requests, the query should be supplied in the `query` URL parameter, e.g.
/// `http://localhost:3000/graphql?query={hero{name}}`.
///
/// POST requests support both queries and variables. POST a JSON document to
/// this endpoint containing the field `"query"` and optionally `"variables"`.
/// The variables should be a JSON object containing the variable to value
/// mapping.
pub struct GraphQLHandler<
    'a,
    CtxFactory,
    Query,
    Mutation,
    Subscription,
    CtxT,
    S = DefaultScalarValue,
> where
    S: ScalarValue,
    CtxFactory: Fn(&mut Request) -> IronResult<CtxT> + Send + Sync + 'static,
    CtxT: 'static,
    Query: GraphQLType<S, Context = CtxT> + Send + Sync + 'static,
    Mutation: GraphQLType<S, Context = CtxT> + Send + Sync + 'static,
    Subscription: GraphQLType<S, Context = CtxT> + Send + Sync + 'static,
{
    context_factory: CtxFactory,
    root_node: RootNode<'a, Query, Mutation, Subscription, S>,
}

/// Handler that renders `GraphiQL` - a graphical query editor interface
pub struct GraphiQLHandler {
    graphql_url: String,
    subscription_url: Option<String>,
}

/// Handler that renders `GraphQL Playground` - a graphical query editor interface
pub struct PlaygroundHandler {
    graphql_url: String,
    subscription_url: Option<String>,
}

fn get_single_value<T>(mut values: Vec<T>) -> IronResult<T> {
    if values.len() == 1 {
        Ok(values.remove(0))
    } else {
        Err(GraphQLIronError::InvalidData("Duplicate URL query parameter").into())
    }
}

fn parse_url_param(params: Option<Vec<String>>) -> IronResult<Option<String>> {
    if let Some(values) = params {
        get_single_value(values).map(Some)
    } else {
        Ok(None)
    }
}

fn parse_variable_param<S>(params: Option<Vec<String>>) -> IronResult<Option<InputValue<S>>>
where
    S: ScalarValue,
{
    if let Some(values) = params {
        Ok(
            serde_json::from_str::<InputValue<S>>(get_single_value(values)?.as_ref())
                .map(Some)
                .map_err(GraphQLIronError::Serde)?,
        )
    } else {
        Ok(None)
    }
}

impl<'a, CtxFactory, Query, Mutation, Subscription, CtxT, S>
    GraphQLHandler<'a, CtxFactory, Query, Mutation, Subscription, CtxT, S>
where
    S: ScalarValue + Send + Sync + 'static,
    CtxFactory: Fn(&mut Request) -> IronResult<CtxT> + Send + Sync + 'static,
    CtxT: Send + Sync + 'static,
    Query: GraphQLType<S, Context = CtxT, TypeInfo = ()> + Send + Sync + 'static,
    Mutation: GraphQLType<S, Context = CtxT, TypeInfo = ()> + Send + Sync + 'static,
    Subscription: GraphQLType<S, Context = CtxT, TypeInfo = ()> + Send + Sync + 'static,
{
    /// Build a new GraphQL handler
    ///
    /// The context factory will receive the Iron request object and is
    /// expected to construct a context object for the given schema. This can
    /// be used to construct e.g. database connections or similar data that
    /// the schema needs to execute the query.
    pub fn new(
        context_factory: CtxFactory,
        query: Query,
        mutation: Mutation,
        subscription: Subscription,
    ) -> Self {
        GraphQLHandler {
            context_factory,
            root_node: RootNode::new_with_scalar_value(query, mutation, subscription),
        }
    }

    fn handle_get(&self, req: &mut Request) -> IronResult<GraphQLBatchRequest<S>> {
        let url_query = req
            .get_mut::<UrlEncodedQuery>()
            .map_err(GraphQLIronError::Url)?;

        let query = parse_url_param(url_query.remove("query"))?
            .ok_or_else(|| GraphQLIronError::InvalidData("No query provided"))?;
        let operation_name = parse_url_param(url_query.remove("operationName"))?;
        let variables = parse_variable_param(url_query.remove("variables"))?;

        Ok(GraphQLBatchRequest::Single(http::GraphQLRequest::new(
            query,
            operation_name,
            variables,
        )))
    }

    fn handle_post_json(&self, req: &mut Request) -> IronResult<GraphQLBatchRequest<S>> {
        let mut payload = String::new();
        itry!(req.body.read_to_string(&mut payload));

        Ok(
            serde_json::from_str::<GraphQLBatchRequest<S>>(payload.as_str())
                .map_err(GraphQLIronError::Serde)?,
        )
    }

    fn handle_post_graphql(&self, req: &mut Request) -> IronResult<GraphQLBatchRequest<S>> {
        let mut payload = String::new();
        itry!(req.body.read_to_string(&mut payload));

        Ok(GraphQLBatchRequest::Single(http::GraphQLRequest::new(
            payload, None, None,
        )))
    }

    fn execute_sync(
        &self,
        context: &CtxT,
        request: GraphQLBatchRequest<S>,
    ) -> IronResult<Response> {
        let response = request.execute_sync(&self.root_node, context);
        let content_type = "application/json".parse::<Mime>().unwrap();
        let json = serde_json::to_string_pretty(&response).unwrap();
        let status = if response.is_ok() {
            status::Ok
        } else {
            status::BadRequest
        };
        Ok(Response::with((content_type, status, json)))
    }
}

impl GraphiQLHandler {
    /// Build a new GraphiQL handler targeting the specified URL.
    ///
    /// The provided URL should point to the URL of the attached `GraphQLHandler`. It can be
    /// relative, so a common value could be `"/graphql"`.
    pub fn new(graphql_url: &str, subscription_url: Option<&str>) -> GraphiQLHandler {
        GraphiQLHandler {
            graphql_url: graphql_url.to_owned(),
            subscription_url: subscription_url.map(|s| s.to_owned()),
        }
    }
}

impl PlaygroundHandler {
    /// Build a new GraphQL Playground handler targeting the specified URL.
    ///
    /// The provided URL should point to the URL of the attached `GraphQLHandler`. It can be
    /// relative, so a common value could be `"/graphql"`.
    pub fn new(graphql_url: &str, subscription_url: Option<&str>) -> PlaygroundHandler {
        PlaygroundHandler {
            graphql_url: graphql_url.to_owned(),
            subscription_url: subscription_url.map(|s| s.to_owned()),
        }
    }
}

impl<'a, CtxFactory, Query, Mutation, Subscription, CtxT, S> Handler
    for GraphQLHandler<'a, CtxFactory, Query, Mutation, Subscription, CtxT, S>
where
    S: ScalarValue + Sync + Send + 'static,
    CtxFactory: Fn(&mut Request) -> IronResult<CtxT> + Send + Sync + 'static,
    CtxT: Send + Sync + 'static,
    Query: GraphQLType<S, Context = CtxT, TypeInfo = ()> + Send + Sync + 'static,
    Mutation: GraphQLType<S, Context = CtxT, TypeInfo = ()> + Send + Sync + 'static,
    Subscription: GraphQLType<S, Context = CtxT, TypeInfo = ()> + Send + Sync + 'static,
    'a: 'static,
{
    fn handle(&self, mut req: &mut Request) -> IronResult<Response> {
        let context = (self.context_factory)(req)?;

        let graphql_request = match req.method {
            method::Get => self.handle_get(&mut req)?,
            method::Post => match req.headers.get::<ContentType>().map(ContentType::deref) {
                Some(Mime(TopLevel::Application, sub_lvl, _)) => match sub_lvl.as_str() {
                    "json" => self.handle_post_json(&mut req)?,
                    "graphql" => self.handle_post_graphql(&mut req)?,
                    _ => return Ok(Response::with(status::BadRequest)),
                },
                _ => return Ok(Response::with(status::BadRequest)),
            },
            _ => return Ok(Response::with(status::MethodNotAllowed)),
        };

        self.execute_sync(&context, graphql_request)
    }
}

impl Handler for GraphiQLHandler {
    fn handle(&self, _: &mut Request) -> IronResult<Response> {
        let content_type = "text/html; charset=utf-8".parse::<Mime>().unwrap();

        Ok(Response::with((
            content_type,
            status::Ok,
            juniper::http::graphiql::graphiql_source(
                &self.graphql_url,
                self.subscription_url.as_deref(),
            ),
        )))
    }
}

impl Handler for PlaygroundHandler {
    fn handle(&self, _: &mut Request) -> IronResult<Response> {
        let content_type = "text/html; charset=utf-8".parse::<Mime>().unwrap();

        Ok(Response::with((
            content_type,
            status::Ok,
            juniper::http::playground::playground_source(
                &self.graphql_url,
                self.subscription_url.as_deref(),
            ),
        )))
    }
}

#[derive(Debug)]
enum GraphQLIronError {
    Serde(SerdeError),
    Url(UrlDecodingError),
    InvalidData(&'static str),
}

impl fmt::Display for GraphQLIronError {
    fn fmt(&self, mut f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            GraphQLIronError::Serde(ref err) => fmt::Display::fmt(err, &mut f),
            GraphQLIronError::Url(ref err) => fmt::Display::fmt(err, &mut f),
            GraphQLIronError::InvalidData(err) => fmt::Display::fmt(err, &mut f),
        }
    }
}

impl Error for GraphQLIronError {
    fn cause(&self) -> Option<&dyn Error> {
        match *self {
            GraphQLIronError::Serde(ref err) => Some(err),
            GraphQLIronError::Url(ref err) => Some(err),
            GraphQLIronError::InvalidData(_) => None,
        }
    }
}

impl From<GraphQLIronError> for IronError {
    fn from(err: GraphQLIronError) -> IronError {
        let message = format!("{}", err);
        IronError::new(err, (status::BadRequest, message))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use iron::{
        headers::ContentType,
        mime::{Mime, SubLevel, TopLevel},
        Handler, Headers, Url,
    };
    use iron_test::{request, response};
    use percent_encoding::{utf8_percent_encode, AsciiSet, CONTROLS};

    use juniper::{
        http::tests as http_tests,
        tests::fixtures::starwars::schema::{Database, Query},
        DefaultScalarValue, EmptyMutation, EmptySubscription,
    };

    use super::GraphQLHandler;

    /// https://url.spec.whatwg.org/#query-state
    const QUERY_ENCODE_SET: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'#').add(b'<').add(b'>');

    // This is ugly but it works. `iron_test` just dumps the path/url in headers
    // and newer `hyper` doesn't allow unescaped "{" or "}".
    fn fixup_url(url: &str) -> String {
        let url = Url::parse(&format!("http://localhost:3000{}", url)).expect("url to parse");
        let path: String = url
            .path()
            .iter()
            .map(|x| (*x).to_string())
            .collect::<Vec<_>>()
            .join("/");
        format!(
            "http://localhost:3000{}?{}",
            path,
            utf8_percent_encode(url.query().unwrap_or(""), QUERY_ENCODE_SET)
        )
    }

    struct TestIronIntegration;

    impl http_tests::HttpIntegration for TestIronIntegration {
        fn get(&self, url: &str) -> http_tests::TestResponse {
            request::get(&fixup_url(url), Headers::new(), &make_handler())
                .map(make_test_response)
                .unwrap_or_else(make_test_error_response)
        }

        fn post_json(&self, url: &str, body: &str) -> http_tests::TestResponse {
            let mut headers = Headers::new();
            headers.set(ContentType::json());
            request::post(&fixup_url(url), headers, body, &make_handler())
                .map(make_test_response)
                .unwrap_or_else(make_test_error_response)
        }

        fn post_graphql(&self, url: &str, body: &str) -> http_tests::TestResponse {
            let mut headers = Headers::new();
            headers.set(ContentType(Mime(
                TopLevel::Application,
                SubLevel::Ext("graphql".into()),
                vec![],
            )));
            request::post(&fixup_url(url), headers, body, &make_handler())
                .map(make_test_response)
                .unwrap_or_else(make_test_error_response)
        }
    }

    #[test]
    fn test_iron_integration() {
        let integration = TestIronIntegration;

        http_tests::run_http_test_suite(&integration);
    }

    fn context_factory(_: &mut Request) -> IronResult<Database> {
        Ok(Database::new())
    }

    fn make_test_error_response(_: IronError) -> http_tests::TestResponse {
        // For now all errors return the same status code.
        // `juniper_iron` users can choose to do something different if desired.
        http_tests::TestResponse {
            status_code: 400,
            body: None,
            content_type: "application/json".to_string(),
        }
    }

    fn make_test_response(response: Response) -> http_tests::TestResponse {
        let status_code = response
            .status
            .expect("No status code returned from handler")
            .to_u16() as i32;
        let content_type = String::from_utf8(
            response
                .headers
                .get_raw("content-type")
                .expect("No content type header from handler")[0]
                .clone(),
        )
        .expect("Content-type header invalid UTF-8");
        let body = response::extract_body_to_string(response);

        http_tests::TestResponse {
            status_code,
            body: Some(body),
            content_type,
        }
    }

    fn make_handler() -> Box<dyn Handler> {
        Box::new(<GraphQLHandler<_, _, _, _, _, DefaultScalarValue>>::new(
            context_factory,
            Query,
            EmptyMutation::<Database>::new(),
            EmptySubscription::<Database>::new(),
        ))
    }
}