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
use std::convert::TryInto;
use std::io;
use std::io::ErrorKind;

use async_graphql::http::MultipartOptions;
use async_graphql::{BatchRequest, ObjectType, Schema, SubscriptionType};
use futures_util::TryStreamExt;
use warp::reply::Response as WarpResponse;
use warp::{Buf, Filter, Rejection, Reply};

use crate::BadRequest;

/// GraphQL batch request filter
///
/// It outputs a tuple containing the `async_graphql::Schema` and `async_graphql::BatchRequest`.
pub fn graphql_batch<Query, Mutation, Subscription>(
    schema: Schema<Query, Mutation, Subscription>,
) -> impl Filter<Extract = ((Schema<Query, Mutation, Subscription>, BatchRequest),), Error = Rejection>
       + Clone
where
    Query: ObjectType + Send + Sync + 'static,
    Mutation: ObjectType + Send + Sync + 'static,
    Subscription: SubscriptionType + Send + Sync + 'static,
{
    graphql_batch_opts(schema, Default::default())
}

/// Similar to graphql_batch, but you can set the options with :`async_graphql::MultipartOptions`.
pub fn graphql_batch_opts<Query, Mutation, Subscription>(
    schema: Schema<Query, Mutation, Subscription>,
    opts: MultipartOptions,
) -> impl Filter<Extract = ((Schema<Query, Mutation, Subscription>, BatchRequest),), Error = Rejection>
       + Clone
where
    Query: ObjectType + Send + Sync + 'static,
    Mutation: ObjectType + Send + Sync + 'static,
    Subscription: SubscriptionType + Send + Sync + 'static,
{
    warp::any()
        .and(warp::get().and(warp::query()).map(BatchRequest::Single))
        .or(warp::post()
            .and(warp::header::optional::<String>("content-type"))
            .and(warp::body::stream())
            .and_then(move |content_type, body| async move {
                async_graphql::http::receive_batch_body(
                    content_type,
                    TryStreamExt::map_err(body, |e| io::Error::new(ErrorKind::Other, e))
                        .map_ok(|mut buf| Buf::to_bytes(&mut buf))
                        .into_async_read(),
                    opts,
                )
                .await
                .map_err(|e| warp::reject::custom(BadRequest(e)))
            }))
        .unify()
        .map(move |res| (schema.clone(), res))
}

/// Reply for `async_graphql::BatchRequest`.
#[derive(Debug)]
pub struct BatchResponse(pub async_graphql::BatchResponse);

impl From<async_graphql::BatchResponse> for BatchResponse {
    fn from(resp: async_graphql::BatchResponse) -> Self {
        BatchResponse(resp)
    }
}

impl Reply for BatchResponse {
    fn into_response(self) -> WarpResponse {
        let mut resp = warp::reply::with_header(
            warp::reply::json(&self.0),
            "content-type",
            "application/json",
        )
        .into_response();

        if self.0.is_ok() {
            if let Some(cache_control) = self.0.cache_control().value() {
                resp.headers_mut()
                    .insert("cache-control", cache_control.try_into().unwrap());
            }
        }

        resp
    }
}