-
Notifications
You must be signed in to change notification settings - Fork 749
Expand file tree
/
Copy pathGraphQLGETTransformer.swift
More file actions
63 lines (49 loc) · 1.77 KB
/
GraphQLGETTransformer.swift
File metadata and controls
63 lines (49 loc) · 1.77 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
//
// GraphQLGETTransformer.swift
// Apollo
//
// Created by Ellen Shapiro on 7/1/19.
// Copyright © 2019 Apollo GraphQL. All rights reserved.
//
import Foundation
struct GraphQLGETTransformer {
let body: GraphQLMap
let url: URL
private let variablesKey = "variables"
private let queryKey = "query"
/// A helper for transforming a GraphQLMap that can be sent with a `POST` request into a URL with query parameters for a `GET` request.
///
/// - Parameters:
/// - body: The GraphQLMap to transform from the body of a `POST` request
/// - url: The base url to append the query to.
init(body: GraphQLMap,
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.
func createGetURL() -> URL? {
guard var components = URLComponents(string: self.url.absoluteString) else {
return nil
}
guard let query = self.body.jsonObject[self.queryKey] as? String else {
return nil
}
var queryItems = components.queryItems ?? [URLQueryItem]()
queryItems.append(URLQueryItem(name: self.queryKey, value: query))
components.queryItems = queryItems
guard let variables = self.body.jsonObject[self.variablesKey] as? [String: Any] else {
return components.url
}
guard
let serializedData = try? JSONSerialization.dataSortedIfPossible(withJSONObject: variables),
let jsonString = String(bytes: serializedData, encoding: .utf8) else {
return components.url
}
queryItems.append(URLQueryItem(name: self.variablesKey, value: jsonString))
components.queryItems = queryItems
return components.url
}
}