From 9636d6eeaa9ff7103c94dc18814560a671e8e252 Mon Sep 17 00:00:00 2001 From: gh-action-runner Date: Tue, 21 Nov 2023 19:57:16 +0000 Subject: [PATCH] Squashed 'apollo-ios/' changes from 7b26cd87..9ec294fb 9ec294fb Adding GraphQLResult conversion extension (apollographql/apollo-ios-dev#139) git-subtree-dir: apollo-ios git-subtree-split: 9ec294fbf63e32c66e2ca1f2b36f3d1b72c7010c --- Sources/Apollo/GraphQLError.swift | 11 +++++++++++ Sources/Apollo/GraphQLResult.swift | 29 +++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/Sources/Apollo/GraphQLError.swift b/Sources/Apollo/GraphQLError.swift index 94b505745..6c99dea41 100644 --- a/Sources/Apollo/GraphQLError.swift +++ b/Sources/Apollo/GraphQLError.swift @@ -86,3 +86,14 @@ extension GraphQLError: LocalizedError { return self.description } } + +extension GraphQLError { + func asJSONDictionary() -> [String: Any] { + var dict: [String: Any] = [:] + if let message = self["message"] { dict["message"] = message } + if let locations = self["locations"] { dict["locations"] = locations } + if let path = self["path"] { dict["path"] = path } + if let extensions = self["extensions"] { dict["extensions"] = extensions } + return dict + } +} diff --git a/Sources/Apollo/GraphQLResult.swift b/Sources/Apollo/GraphQLResult.swift index dac207681..f602a0921 100644 --- a/Sources/Apollo/GraphQLResult.swift +++ b/Sources/Apollo/GraphQLResult.swift @@ -47,3 +47,32 @@ extension GraphQLResult: Equatable where Data: Equatable { } extension GraphQLResult: Hashable where Data: Hashable {} + +extension GraphQLResult { + + /// Converts a ``GraphQLResult`` into a basic JSON dictionary for use. + /// + /// - Returns: A `[String: Any]` JSON dictionary representing the ``GraphQLResult``. + public func asJSONDictionary() -> [String: Any] { + var dict: [String: Any] = [:] + if let data { dict["data"] = convert(value: data.__data) } + if let errors { dict["errors"] = errors.map { $0.asJSONDictionary() } } + if let extensions { dict["extensions"] = extensions } + return dict + } + + private func convert(value: Any) -> Any { + var val: Any = value + if let value = value as? ApolloAPI.DataDict { + val = value._data + } else if let value = value as? CustomScalarType { + val = value._jsonValue + } + if let dict = val as? [String: Any] { + return dict.mapValues(convert) + } else if let arr = val as? [Any] { + return arr.map(convert) + } + return val + } +}