-
Notifications
You must be signed in to change notification settings - Fork 749
Expand file tree
/
Copy pathGraphQLGETTransformer.swift
More file actions
71 lines (59 loc) · 2.14 KB
/
GraphQLGETTransformer.swift
File metadata and controls
71 lines (59 loc) · 2.14 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import Foundation
#if !COCOAPODS
import ApolloMigrationAPI
#endif
public struct GraphQLGETTransformer {
let body: JSONEncodableDictionary
let url: URL
/// A helper for transforming a `JSONEncodableDictionary` that can be sent with a `POST` request into a URL with query parameters for a `GET` request.
///
/// - Parameters:
/// - body: The `JSONEncodableDictionary` to transform from the body of a `POST` request
/// - url: The base url to append the query to.
public init(body: JSONEncodableDictionary, url: URL) {
self.body = body
self.url = url
}
/// Creates the get URL.
///
/// - Returns: [optional] The created get URL or nil if the provided information couldn't be used to access the appropriate parameters.
public func createGetURL() -> URL? {
guard var components = URLComponents(string: self.url.absoluteString) else {
return nil
}
var queryItems: [URLQueryItem] = components.queryItems ?? []
do {
_ = try self.body.sorted(by: {$0.key < $1.key}).compactMap({ arg in
if let value = arg.value as? JSONEncodableDictionary {
let data = try JSONSerialization.sortedData(withJSONObject: value._jsonValue)
if let string = String(data: data, encoding: .utf8) {
queryItems.append(URLQueryItem(name: arg.key, value: string))
}
} else if let string = arg.value as? String {
queryItems.append(URLQueryItem(name: arg.key, value: string))
} else if (arg.key != "variables") {
assertionFailure()
}
})
} catch {
return nil
}
if !queryItems.isEmpty {
components.queryItems = queryItems
}
components.percentEncodedQuery =
components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
return components.url
}
}
// MARK: - Hashable Conformance
extension GraphQLGETTransformer: Hashable {
public static func == (lhs: GraphQLGETTransformer, rhs: GraphQLGETTransformer) -> Bool {
lhs.body._jsonValue == rhs.body._jsonValue &&
lhs.url == rhs.url
}
public func hash(into hasher: inout Hasher) {
hasher.combine(body._jsonValue)
hasher.combine(url)
}
}