mockql_core/graphql/
response_validator.rs1use apollo_compiler::ExecutableDocument;
18use apollo_compiler::Schema;
19use apollo_compiler::ast::Type;
20use apollo_compiler::resolvers::Execution;
21use apollo_compiler::resolvers::FieldError;
22use apollo_compiler::resolvers::ObjectValue;
23use apollo_compiler::resolvers::ResolveInfo;
24use apollo_compiler::resolvers::ResolvedValue;
25use apollo_compiler::response::GraphQLError;
26use apollo_compiler::response::JsonMap;
27use apollo_compiler::response::JsonValue;
28use apollo_compiler::validation::Valid;
29use serde_json_bytes::ByteString;
30use serde_json_bytes::Map;
31use serde_json_bytes::Value;
32use std::sync::Arc;
33
34#[derive(Debug, Clone)]
37pub(crate) struct ResponseValidator {
38 schema: Arc<Valid<Schema>>,
39}
40
41#[derive(Debug, thiserror::Error)]
43pub enum ResponseValidationError {
44 #[error("invalid GraphQL request: {0}")]
46 InvalidRequest(String),
47 #[error("response data must be a JSON object")]
49 InvalidData,
50 #[error("response validation failed: {0:?}")]
52 Execution(Vec<GraphQLError>),
53}
54
55impl ResponseValidator {
56 pub(crate) fn new(schema: Arc<Valid<Schema>>) -> Self {
58 Self { schema }
59 }
60
61 pub(crate) fn validate(
63 &self,
64 document: &Valid<ExecutableDocument>,
65 operation_name: Option<&str>,
66 variables: &Map<ByteString, Value>,
67 data: &Value,
68 ) -> Result<Value, ResponseValidationError> {
69 let root_object = data.as_object().ok_or(ResponseValidationError::InvalidData)?;
70 let operation = document
71 .operations
72 .get(operation_name)
73 .map_err(|error| ResponseValidationError::InvalidRequest(error.message().to_string()))?;
74
75 let response = Execution::new(&self.schema, document)
76 .operation(operation)
77 .raw_variable_values(variables)
78 .execute_sync(&JsonObject {
79 type_name: operation.selection_set.ty.as_str(),
80 object: root_object,
81 })
82 .map_err(|error| ResponseValidationError::InvalidRequest(error.message().to_string()))?;
83
84 if !response.errors.is_empty() {
85 return Err(ResponseValidationError::Execution(response.errors));
86 }
87
88 response
89 .data
90 .map(Value::Object)
91 .ok_or(ResponseValidationError::InvalidData)
92 }
93}
94
95struct JsonObject<'a> {
96 type_name: &'a str,
97 object: &'a JsonMap,
98}
99
100impl ObjectValue for JsonObject<'_> {
101 fn type_name(&self) -> &str {
102 self.type_name
103 }
104
105 fn resolve_field<'a>(&'a self, info: &'a ResolveInfo<'a>) -> Result<ResolvedValue<'a>, FieldError> {
106 let response_key = info.field_selections()[0].response_key();
107 match self.object.get(response_key.as_str()) {
108 Some(value) => resolve_value(value, info),
109 None => Ok(ResolvedValue::null()),
110 }
111 }
112}
113
114fn resolve_value<'a>(value: &'a JsonValue, info: &'a ResolveInfo<'a>) -> Result<ResolvedValue<'a>, FieldError> {
115 resolve_typed_value(value, &info.field_definition().ty, info)
116}
117
118fn resolve_typed_value<'a>(
119 value: &'a JsonValue,
120 ty: &'a Type,
121 info: &'a ResolveInfo<'a>,
122) -> Result<ResolvedValue<'a>, FieldError> {
123 if ty.is_list() {
124 return match value {
125 JsonValue::Array(values) => Ok(ResolvedValue::List(Box::new(
126 values
127 .iter()
128 .map(move |value| resolve_typed_value(value, ty.item_type(), info)),
129 ))),
130 value => Ok(ResolvedValue::leaf(value.clone())),
131 };
132 }
133
134 let type_name = ty.inner_named_type();
135 let type_definition = &info.schema().types[type_name];
136 if type_definition.is_scalar() || type_definition.is_enum() {
137 return Ok(ResolvedValue::leaf(normalize_leaf(value, type_name.as_str())));
138 }
139
140 match value {
141 JsonValue::Object(object) => Ok(ResolvedValue::object(JsonObject {
142 type_name: object
143 .get("__typename")
144 .and_then(JsonValue::as_str)
145 .unwrap_or(type_name.as_str()),
146 object,
147 })),
148 value => Ok(ResolvedValue::leaf(value.clone())),
149 }
150}
151
152fn normalize_leaf(value: &JsonValue, type_name: &str) -> JsonValue {
153 match type_name {
154 "Float" if !value.is_f64() => value
155 .as_i64()
156 .and_then(|integer| {
157 let float = integer as f64;
158 (integer != i64::MAX && float as i64 == integer).then_some(float)
159 })
160 .or_else(|| {
161 value.as_u64().and_then(|integer| {
162 let float = integer as f64;
163 (integer != u64::MAX && float as u64 == integer).then_some(float)
164 })
165 })
166 .map_or_else(|| value.clone(), JsonValue::from),
167 "ID" => value
168 .as_i64()
169 .map_or_else(|| value.clone(), |integer| JsonValue::from(integer.to_string())),
170 _ => value.clone(),
171 }
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177 use serde_json::Value as JsonValue;
178 use serde_json::from_str;
179 use std::fs::read_to_string;
180
181 fn parse_fixture(content: &str) -> (String, Value) {
182 let mut fixture: serde_json::Map<String, JsonValue> = from_str(content).expect("should parse fixture JSON");
183 (
184 serde_json::from_value(
185 fixture
186 .remove("operation")
187 .expect("fixture should have 'operation' key"),
188 )
189 .expect("should deserialize 'operation' string"),
190 serde_json::from_value(fixture.remove("data").expect("fixture should have 'data' key"))
191 .expect("should deserialize response data"),
192 )
193 }
194
195 fn snapshot(result: Result<Value, ResponseValidationError>) -> String {
196 let value = match result {
197 Ok(data) => serde_json::json!({ "data": data }),
198 Err(ResponseValidationError::Execution(errors)) => serde_json::json!({ "errors": errors }),
199 Err(error) => serde_json::json!({ "error": error.to_string() }),
200 };
201 serde_json::to_string_pretty(&value).expect("snapshot value should serialize")
202 }
203
204 #[test]
205 fn validate_response() {
206 insta::glob!("snapshots/response_validator/*.json", |path| {
207 let (operation, data) = parse_fixture(&read_to_string(path).expect("should read fixture file"));
208 let schema = Schema::parse_and_validate(
209 concat!(
210 include_str!("schema.graphql"),
211 "scalar JSON extend type Query { config: JSON!, configs: [JSON!]! }"
212 ),
213 "schema.graphql",
214 )
215 .expect("test schema should be valid");
216 let document = ExecutableDocument::parse_and_validate(&schema, &operation, "operation.graphql")
217 .expect("test operation should be valid");
218 let result = ResponseValidator::new(Arc::new(schema)).validate(&document, None, &Map::new(), &data);
219
220 insta::with_settings!({snapshot_path => path.parent().unwrap(), omit_expression => true}, {
221 insta::assert_snapshot!(snapshot(result));
222 });
223 });
224 }
225}