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
use crate::execution::engine::PropagateNull;
use crate::execution::JsonMap;
use crate::parser::LineColumn;
use crate::parser::SourceMap;
use crate::parser::SourceSpan;
use serde::Deserialize;
use serde::Serialize;

/// A [GraphQL response](https://spec.graphql.org/October2021/#sec-Response-Format)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Response {
    // <https://spec.graphql.org/October2021/#note-6f005> suggests serializing this first
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde(default)]
    pub errors: Vec<GraphQLError>,

    #[serde(skip_serializing_if = "ResponseData::is_absent")]
    #[serde(default = "ResponseData::absent")]
    pub data: ResponseData,

    /// Reserved for any additional information
    #[serde(skip_serializing_if = "JsonMap::is_empty")]
    #[serde(default)]
    pub extensions: JsonMap,
}

/// The `data` entry of a [`Response`]
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(from = "Option<JsonMap>")]
pub enum ResponseData {
    /// Execution returned an object.
    /// [`Response::data`] is serialized as a JSON object.
    Object(JsonMap),

    /// Execution encountered a [field error] on a non-null field,
    /// and null was [propagated] all the way to the root of the response.
    /// [`Response::data`] is serialized as JSON null.
    ///
    /// [field error]: https://spec.graphql.org/October2021/#sec-Errors.Field-errors
    /// [propagated]: https://spec.graphql.org/October2021/#sec-Handling-Field-Errors
    Null,

    /// A [request error] was encountered. Execution did not start.
    /// [`Response::data`] is skipped from serialization.
    ///
    /// [request error]: https://spec.graphql.org/October2021/#sec-Errors.Request-errors
    Absent,
}

/// A serializable [error](https://spec.graphql.org/October2021/#sec-Errors.Error-result-format),
/// as found in a GraphQL [response][Response].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GraphQLError {
    /// The error message.
    pub message: String,

    /// Locations in relevant to the error, if any.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde(default)]
    pub locations: Vec<LineColumn>,

    /// If non-empty, the error is a [field error]
    /// for the particular field found at this path in [`Response::data`].
    ///
    /// [field error]: https://spec.graphql.org/October2021/#sec-Errors.Field-errors
    #[serde(skip_serializing_if = "Vec::is_empty")]
    #[serde(default)]
    pub path: Vec<ResponseDataPathElement>,

    /// Reserved for any additional information
    #[serde(skip_serializing_if = "JsonMap::is_empty")]
    #[serde(default)]
    pub extensions: JsonMap,
}

/// An element of [`GraphQLError::path`]
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ResponseDataPathElement {
    /// The relevant key in an object value
    Field(crate::Name),

    /// The index of the relevant item in a list value
    ListIndex(usize),
}

impl Response {
    /// Create a response for a [request error]:
    /// handling of a request was aborted before execution started.
    ///
    /// [request error]: https://spec.graphql.org/October2021/#sec-Errors.Request-errors
    pub fn from_request_error(error: impl Into<GraphQLError>) -> Self {
        Self {
            errors: vec![error.into()],
            data: ResponseData::Absent,
            extensions: JsonMap::new(),
        }
    }

    /// Merge two responses into one, such as to handle
    /// [`SchemaIntrospectionSplit::Both`][crate::execution::SchemaIntrospectionSplit::Both].
    pub fn merge(mut self, mut other: Self) -> Self {
        match (&mut self.data, other.data) {
            (ResponseData::Absent, _) | (_, ResponseData::Absent) => {
                // If either side is a request error (absent data), return a request error
                self.data = ResponseData::Absent
            }
            (ResponseData::Null, _) | (_, ResponseData::Null) => {
                // Otherwise if either side propagated null from a field error
                // to the root of the response, return null data.
                self.data = ResponseData::Null
            }
            (ResponseData::Object(self_data), ResponseData::Object(other_data)) => {
                // Merge two objects/maps
                self_data.extend(other_data)
            }
        }
        self.errors.append(&mut other.errors);
        self.extensions.extend(other.extensions);
        self
    }
}

impl GraphQLError {
    pub fn new(
        message: impl Into<String>,
        location: Option<SourceSpan>,
        sources: &SourceMap,
    ) -> Self {
        Self {
            message: message.into(),
            locations: location
                .into_iter()
                .filter_map(|location| location.line_column(sources))
                .collect(),
            path: Default::default(),
            extensions: Default::default(),
        }
    }
}

impl ResponseData {
    /// For serde `skip_serializing_if`
    pub fn is_absent(&self) -> bool {
        matches!(self, Self::Absent)
    }

    /// For serde `default`
    fn absent() -> Self {
        Self::Absent
    }
}

impl Serialize for ResponseData {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            ResponseData::Absent => panic!("ResponseData::None should not be serialized"),
            ResponseData::Null => serializer.serialize_unit(),
            ResponseData::Object(map) => map.serialize(serializer),
        }
    }
}

impl From<Option<JsonMap>> for ResponseData {
    fn from(value: Option<JsonMap>) -> Self {
        match value {
            Some(data) => Self::Object(data),
            None => Self::Null,
        }
    }
}

impl From<Result<JsonMap, PropagateNull>> for ResponseData {
    fn from(result: Result<JsonMap, PropagateNull>) -> Self {
        match result {
            Ok(data) => Self::Object(data),
            Err(PropagateNull) => Self::Null,
        }
    }
}