-
Notifications
You must be signed in to change notification settings - Fork 739
/
Copy pathGraphQLResponse.swift
40 lines (33 loc) · 1.56 KB
/
GraphQLResponse.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/// Represents a GraphQL response received from a server.
public final class GraphQLResponse<Operation: GraphQLOperation> {
public let operation: Operation
public let body: JSONObject
public init(operation: Operation, body: JSONObject) {
self.operation = operation
self.body = body
}
func parseResult(cacheKeyForObject: CacheKeyForObject? = nil) throws -> Promise<(GraphQLResult<Operation.Data>, RecordSet?)> {
let errors: [GraphQLError]?
if let errorsEntry = body["errors"] as? [JSONObject] {
errors = errorsEntry.map(GraphQLError.init)
} else {
errors = nil
}
if let dataEntry = body["data"] as? JSONObject {
let executor = GraphQLExecutor { object, info in
return .result(.success(object[info.responseKeyForField]))
}
executor.cacheKeyForObject = cacheKeyForObject
let mapper = GraphQLSelectionSetMapper<Operation.Data>()
let normalizer = GraphQLResultNormalizer()
let dependencyTracker = GraphQLDependencyTracker()
return firstly {
try executor.execute(selections: Operation.Data.selections, on: dataEntry, withKey: rootCacheKey(for: operation), variables: operation.variables, accumulator: zip(mapper, normalizer, dependencyTracker))
}.map { (data, records, dependentKeys) in
(GraphQLResult(data: data, errors: errors, source: .server, dependentKeys: dependentKeys), records)
}
} else {
return Promise(fulfilled: (GraphQLResult(data: nil, errors: errors, source: .server, dependentKeys: nil), nil))
}
}
}