1use serde_json_bytes::ByteString;
18use serde_json_bytes::Map;
19use serde_json_bytes::Value;
20
21pub trait MergeableResponse {
24 fn data_mut(&mut self) -> &mut Option<Value>;
26 fn extensions_mut(&mut self) -> &mut Map<ByteString, Value>;
28 fn take_errors_from(&mut self, source: &mut Self);
30}
31
32#[derive(Debug, thiserror::Error)]
34pub enum ResponseMergerError {
35 #[error("non-mergeable keys at path: {path}: {details}")]
37 NonMergeableKeys {
38 path: String,
40 details: String,
42 },
43 #[error("non-mergeable arrays because their lengths differ at path: {path} (into: {into}, from: {from})")]
45 MismatchedArrayLengths {
46 path: String,
48 into: usize,
50 from: usize,
52 },
53 #[error("found invalid type in '{0}' response, expected data to be an object or null")]
55 InvalidDataValueType(String),
56}
57
58fn type_name(value: &Value) -> &'static str {
59 match value {
60 Value::Null => "null",
61 Value::Bool(_) => "bool",
62 Value::Number(_) => "number",
63 Value::String(_) => "string",
64 Value::Array(_) => "array",
65 Value::Object(_) => "object",
66 }
67}
68
69#[derive(Debug)]
71pub struct ResponseMerger;
72
73impl ResponseMerger {
74 pub fn merge<T: MergeableResponse>(into: &mut T, from: &mut T) -> Result<(), ResponseMergerError> {
76 if matches!(into.data_mut(), Some(value) if !value.is_null() && !value.is_object()) {
77 return Err(ResponseMergerError::InvalidDataValueType("into".into()));
78 }
79 if matches!(from.data_mut(), Some(value) if !value.is_null() && !value.is_object()) {
80 return Err(ResponseMergerError::InvalidDataValueType("from".into()));
81 }
82
83 let into_data = into.data_mut().take();
84 let from_data = from.data_mut().take();
85
86 *into.data_mut() = match (into_data, from_data) {
87 (Some(Value::Object(mut into_map)), Some(Value::Object(from_map))) => {
88 Self::merge_objects(&mut into_map, from_map, "")?;
89 Some(Value::Object(into_map))
90 }
91 (Some(data), _) | (_, Some(data)) if data.is_object() => Some(data),
92 _ => None,
93 };
94
95 into.take_errors_from(from);
96
97 let from_extensions = std::mem::take(from.extensions_mut());
98 for (key, value) in from_extensions {
99 let ext = into.extensions_mut();
100 if !ext.contains_key(&key) {
101 ext.insert(key, value);
102 }
103 }
104
105 Ok(())
106 }
107
108 fn merge_objects(
109 into: &mut Map<ByteString, Value>,
110 from: Map<ByteString, Value>,
111 path: &str,
112 ) -> Result<(), ResponseMergerError> {
113 for (from_key, from_value) in from {
114 match (into.get_mut(&from_key), from_value) {
115 (None, from_value) => {
117 into.insert(from_key, from_value);
118 }
119 (Some(into_value), from_value) => {
121 Self::merge_values(into_value, from_value, &Self::child_path(path, from_key.as_str()))?;
122 }
123 }
124 }
125 Ok(())
126 }
127
128 fn merge_values(into: &mut Value, from: Value, path: &str) -> Result<(), ResponseMergerError> {
129 match (into, from) {
130 (Value::Object(into_map), Value::Object(from_map)) => Self::merge_objects(into_map, from_map, path),
131 (Value::Null, from @ (Value::Object(_) | Value::Array(_))) => Err(ResponseMergerError::NonMergeableKeys {
132 path: path.into(),
133 details: format!(
134 "Upstream GraphQL response returned null for this field, cannot merge mocked {} into null",
135 type_name(&from)
136 ),
137 }),
138 (Value::Array(into_array), Value::Array(from_array)) => Self::merge_arrays(into_array, from_array, path),
139 (lhs, rhs) => Err(ResponseMergerError::NonMergeableKeys {
140 path: path.into(),
141 details: format!(
142 "values cannot be merged (into: {}, from: {})",
143 type_name(lhs),
144 type_name(&rhs)
145 ),
146 }),
147 }
148 }
149
150 fn merge_arrays(into: &mut [Value], from: Vec<Value>, path: &str) -> Result<(), ResponseMergerError> {
151 if into.len() != from.len() {
152 return Err(ResponseMergerError::MismatchedArrayLengths {
153 path: path.into(),
154 into: into.len(),
155 from: from.len(),
156 });
157 }
158
159 for (index, (into_value, from_value)) in into.iter_mut().zip(from).enumerate() {
160 let index = index.to_string();
161 Self::merge_values(into_value, from_value, &Self::child_path(path, &index))?;
162 }
163
164 Ok(())
165 }
166
167 fn child_path(path: &str, key: &str) -> String {
168 if path.is_empty() {
169 key.into()
170 } else {
171 format!("{path}.{key}")
172 }
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179 use crate::graphql::GraphQLResponse;
180 use serde_json::Value as JsonValue;
181 use serde_json::from_str;
182 use std::fs::read_to_string;
183
184 fn parse_fixture(content: &str) -> (GraphQLResponse, GraphQLResponse) {
185 let mut fixture: serde_json::Map<String, JsonValue> = from_str(content).expect("should parse fixture JSON");
186 (
187 serde_json::from_value(fixture.remove("into").expect("fixture should have 'into' key"))
188 .expect("should deserialize 'into' GraphQLResponse"),
189 serde_json::from_value(fixture.remove("from").expect("fixture should have 'from' key"))
190 .expect("should deserialize 'from' GraphQLResponse"),
191 )
192 }
193
194 #[test]
195 fn response_merger_produces_expected_output() {
196 insta::glob!("snapshots/response_merger/[!e]*/*.json", |path| {
197 let (mut into, mut from) = parse_fixture(&read_to_string(path).expect("should read fixture file"));
198 ResponseMerger::merge(&mut into, &mut from).expect("merge should succeed");
199
200 insta::with_settings!({snapshot_path => path.parent().unwrap(), omit_expression => true}, {
201 insta::assert_snapshot!(serde_json::to_string_pretty(&into).unwrap());
202 });
203 });
204 }
205
206 #[test]
207 fn response_merger_produces_expected_error() {
208 insta::glob!("snapshots/response_merger/error_cases/*.json", |path| {
209 let (mut into, mut from) = parse_fixture(&read_to_string(path).expect("should read fixture file"));
210 let err = ResponseMerger::merge(&mut into, &mut from).expect_err("merge should fail");
211
212 insta::with_settings!({snapshot_path => path.parent().unwrap(), omit_expression => true}, {
213 insta::assert_snapshot!(format!("{err:?}"));
214 });
215 });
216 }
217}