Skip to content

Commit

Permalink
Squashed 'apollo-ios/' changes from 7b26cd8..9ec294f
Browse files Browse the repository at this point in the history
9ec294f Adding GraphQLResult conversion extension (#139)

git-subtree-dir: apollo-ios
git-subtree-split: 9ec294f
  • Loading branch information
gh-action-runner authored and gh-action-runner committed Nov 21, 2023
1 parent 5e1aa1b commit 9636d6e
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 9636d6e

Please sign in to comment.