Skip to content

Commit 4c93fa3

Browse files
committed
Support appending lists in DeferredJsonMerger (for @stream)
1 parent 6e40324 commit 4c93fa3

File tree

8 files changed

+2052
-1120
lines changed

8 files changed

+2052
-1120
lines changed

libraries/apollo-runtime/src/commonMain/kotlin/com/apollographql/apollo/internal/DeferredJsonMerger.kt

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -114,29 +114,46 @@ class DeferredJsonMerger {
114114
}
115115

116116
private fun mergeIncrementalData(incrementalItem: JsonMap) {
117-
val id = incrementalItem["id"] as String? ?: error("No id found in incremental item")
118-
val data = incrementalItem["data"] as JsonMap? ?: error("No data found in incremental item")
117+
val id = incrementalItem["id"] as String? ?: error("No id found in incremental result")
118+
val data = incrementalItem["data"] as JsonMap?
119+
val items = incrementalItem["items"] as List<Any>?
119120
val subPath = incrementalItem["subPath"] as List<Any>? ?: emptyList()
120121
val path = (_pendingFragmentIds[id]?.path ?: error("Id '$id' not found in pending results")) + subPath
121122
val mergedData = merged["data"] as JsonMap
122-
val nodeToMergeInto = nodeAtPath(mergedData, path) as MutableJsonMap
123-
deepMerge(nodeToMergeInto, data)
123+
val nodeToMergeInto = nodeAtPath(mergedData, path)
124+
when {
125+
data != null -> {
126+
deepMergeObject(nodeToMergeInto as MutableJsonMap, data)
127+
}
128+
129+
items != null -> {
130+
mergeList(nodeToMergeInto as MutableList<Any>, items)
131+
}
132+
133+
else -> {
134+
error("Neither data nor items found in incremental result")
135+
}
136+
}
124137
}
125138

126-
private fun deepMerge(destination: MutableJsonMap, map: JsonMap) {
127-
for ((key, value) in map) {
139+
private fun deepMergeObject(destination: MutableJsonMap, obj: JsonMap) {
140+
for ((key, value) in obj) {
128141
if (destination.containsKey(key) && destination[key] is MutableMap<*, *>) {
129142
// Objects: merge recursively
130143
val fieldDestination = destination[key] as MutableJsonMap
131144
val fieldMap = value as? JsonMap ?: error("'$key' is an object in destination but not in map")
132-
deepMerge(destination = fieldDestination, map = fieldMap)
145+
deepMergeObject(destination = fieldDestination, obj = fieldMap)
133146
} else {
134147
// Other types: add / overwrite
135148
destination[key] = value
136149
}
137150
}
138151
}
139152

153+
private fun mergeList(destination: MutableList<Any>, items: List<Any>) {
154+
destination.addAll(items)
155+
}
156+
140157
private fun jsonToMap(json: BufferedSource): JsonMap = BufferedSourceJsonReader(json).readAny() as JsonMap
141158

142159

0 commit comments

Comments
 (0)