Skip to content

Commit

Permalink
Adding GraphQLResult conversion extension (apollographql/apollo-ios-d…
Browse files Browse the repository at this point in the history
  • Loading branch information
BobaFetters authored and gh-action-runner committed Nov 21, 2023
1 parent 7b26cd8 commit 9ec294f
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
11 changes: 11 additions & 0 deletions Sources/Apollo/GraphQLError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
29 changes: 29 additions & 0 deletions Sources/Apollo/GraphQLResult.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}

0 comments on commit 9ec294f

Please sign in to comment.