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
use {
    http::{Request, Response, StatusCode},
    serde_json::json,
    std::fmt,
    tsukuyomi::{
        error::{Error, HttpError}, //
        future::{Poll, TryFuture},
        handler::{AllowedMethods, Handler, ModifyHandler},
        input::Input,
        output::ResponseBody,
    },
};

#[derive(Debug)]
pub enum GraphQLParseError {
    InvalidRequestMethod,
    MissingQuery,
    MissingMime,
    InvalidMime,
    ParseJson(serde_json::Error),
    ParseQuery(serde_urlencoded::de::Error),
    DecodeUtf8(std::str::Utf8Error),
}

impl fmt::Display for GraphQLParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            GraphQLParseError::InvalidRequestMethod => f.write_str("the request method is invalid"),
            GraphQLParseError::MissingQuery => f.write_str("missing query"),
            GraphQLParseError::MissingMime => f.write_str("missing content-type"),
            GraphQLParseError::InvalidMime => f.write_str("the content type is invalid."),
            GraphQLParseError::ParseJson(ref e) => e.fmt(f),
            GraphQLParseError::ParseQuery(ref e) => e.fmt(f),
            GraphQLParseError::DecodeUtf8(ref e) => e.fmt(f),
        }
    }
}

impl HttpError for GraphQLParseError {
    type Body = String;

    fn into_response(self, _: &Request<()>) -> Response<Self::Body> {
        let body = json!({
            "errors": [
                {
                    "message": self.to_string(),
                }
            ],
        })
        .to_string();
        Response::builder()
            .status(StatusCode::BAD_REQUEST)
            .header("content-type", "application/json")
            .body(body)
            .expect("should be a valid response")
    }
}

#[derive(Debug)]
pub struct GraphQLError(Error);

impl fmt::Display for GraphQLError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl HttpError for GraphQLError {
    type Body = ResponseBody;

    fn into_response(self, request: &Request<()>) -> Response<Self::Body> {
        let body = json!({
            "errors": [
                {
                    "message": self.to_string(),
                }
            ],
        })
        .to_string();

        let mut response = self.0.into_response(request).map(|_| body.into());

        response.headers_mut().insert(
            http::header::CONTENT_TYPE,
            http::header::HeaderValue::from_static("application/json"),
        );

        response
    }
}

/// Creates a `ModifyHandler` that catches the all kind of errors that the handler throws
/// and converts them into GraphQL errors.
pub fn capture_errors() -> CaptureErrors {
    CaptureErrors(())
}

#[allow(missing_docs)]
#[derive(Debug)]
pub struct CaptureErrors(());

impl<H> ModifyHandler<H> for CaptureErrors
where
    H: Handler,
{
    type Output = H::Output;
    type Handler = GraphQLHandler<H>; // private;

    fn modify(&self, inner: H) -> Self::Handler {
        GraphQLHandler { inner }
    }
}

#[derive(Debug)]
pub struct GraphQLHandler<H> {
    inner: H,
}

impl<H> Handler for GraphQLHandler<H>
where
    H: Handler,
{
    type Output = H::Output;
    type Error = Error;
    type Handle = GraphQLHandle<H::Handle>;

    fn allowed_methods(&self) -> Option<&AllowedMethods> {
        self.inner.allowed_methods()
    }

    fn handle(&self) -> Self::Handle {
        GraphQLHandle {
            inner: self.inner.handle(),
        }
    }
}

#[derive(Debug)]
pub struct GraphQLHandle<H> {
    inner: H,
}

impl<H> TryFuture for GraphQLHandle<H>
where
    H: TryFuture,
{
    type Ok = H::Ok;
    type Error = Error;

    fn poll_ready(&mut self, input: &mut Input<'_>) -> Poll<Self::Ok, Self::Error> {
        self.inner.poll_ready(input).map_err(|err| {
            let err = err.into();
            if err.is::<GraphQLParseError>() || err.is::<GraphQLError>() {
                err
            } else {
                GraphQLError(err).into()
            }
        })
    }
}