|
| 1 | +import Foundation |
| 2 | + |
| 3 | +public final class GraphQLClient { |
| 4 | + private let endpoint: URL |
| 5 | + private let network: NetworkClient |
| 6 | + private let decoder: JSONDecoder |
| 7 | + private let defaultHeaders: [String: String] |
| 8 | + |
| 9 | + public init(endpoint: URL, |
| 10 | + network: NetworkClient = URLSessionNetworkClient(), |
| 11 | + decoder: JSONDecoder = JSONDecoder(), |
| 12 | + defaultHeaders: [String: String] = [ |
| 13 | + "Content-Type": "application/json", |
| 14 | + "Accept": "application/json" |
| 15 | + ]) { |
| 16 | + self.endpoint = endpoint |
| 17 | + self.network = network |
| 18 | + self.decoder = decoder |
| 19 | + self.defaultHeaders = defaultHeaders |
| 20 | + } |
| 21 | + |
| 22 | + /// Execute a GraphQL operation from stirng query |
| 23 | + /// - Parameters: |
| 24 | + /// - query: Query in graphql format |
| 25 | + /// - variables: Codable variables (optional) |
| 26 | + /// - operationName: Operation name (optional) |
| 27 | + /// - headers: Extra headers (merged over defaultHeaders) |
| 28 | + public func execute<Variables: Encodable, Output: Decodable>( |
| 29 | + query: String, |
| 30 | + variables: Variables? = nil, |
| 31 | + operationName: String? = nil, |
| 32 | + headers: [String: String] = [:] |
| 33 | + ) async throws -> Output { |
| 34 | + let gqlRequest = GraphQLRequest(query: query, variables: variables, operationName: operationName) |
| 35 | + var request = URLRequest(url: endpoint) |
| 36 | + request.httpMethod = "POST" |
| 37 | + request.httpBody = try gqlRequest.httpBody() |
| 38 | + |
| 39 | + let combinedHeaders = defaultHeaders.merging(headers) { _, new in new } |
| 40 | + combinedHeaders.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) } |
| 41 | + |
| 42 | + let data = try await network.send(request) |
| 43 | + |
| 44 | + do { |
| 45 | + let envelope = try decoder.decode(GraphQLResponse<Output>.self, from: data) |
| 46 | + if let errors = envelope.errors, !errors.isEmpty { |
| 47 | + throw GraphQLClientError.graphQLErrors(errors) |
| 48 | + } |
| 49 | + guard let value = envelope.data else { |
| 50 | + throw GraphQLClientError.missingData |
| 51 | + } |
| 52 | + return value |
| 53 | + } catch { |
| 54 | + throw GraphQLClientError.decoding(error) |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + /// Execute a GraphQL operation where the query is loaded from a .graphql file in a bundle. |
| 59 | + /// - Parameters: |
| 60 | + /// - resource: Filename without extension (e.g., "GetUser") |
| 61 | + /// - ext: File extension (defaults to "graphql") |
| 62 | + /// - bundle: Bundle to search (defaults to .main) |
| 63 | + /// - variables: Codable variables (optional) |
| 64 | + /// - operationName: Operation name (optional) |
| 65 | + /// - headers: Extra headers (merged over defaultHeaders) |
| 66 | + public func executeFromFile<Variables: Encodable, Output: Decodable>( |
| 67 | + resource: String, |
| 68 | + ext: String = "graphql", |
| 69 | + bundle: Bundle = Bundle.main, |
| 70 | + variables: Variables? = nil, |
| 71 | + operationName: String? = nil, |
| 72 | + headers: [String: String] = [:] |
| 73 | + ) async throws -> Output { |
| 74 | + guard let url = bundle.url(forResource: resource, withExtension: ext) else { |
| 75 | + throw GraphQLClientError.queryFileNotFound("\(resource).\(ext)") |
| 76 | + } |
| 77 | + |
| 78 | + let query: String |
| 79 | + do { |
| 80 | + query = try String(contentsOf: url, encoding: .utf8) |
| 81 | + } catch { |
| 82 | + throw GraphQLClientError.unreadableQueryFile(url, error) |
| 83 | + } |
| 84 | + |
| 85 | + return try await execute( |
| 86 | + query: query, |
| 87 | + variables: variables, |
| 88 | + operationName: operationName, |
| 89 | + headers: headers |
| 90 | + ) |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +/// Standard GraphQL envelope: { data, errors } |
| 95 | +private struct GraphQLResponse<DataType: Decodable>: Decodable { |
| 96 | + let data: DataType? |
| 97 | + let errors: [GraphQLError]? |
| 98 | +} |
| 99 | + |
| 100 | +public enum GraphQLClientError: Error, CustomStringConvertible { |
| 101 | + case graphQLErrors([GraphQLError]) |
| 102 | + case missingData |
| 103 | + case decoding(Error) |
| 104 | + case queryFileNotFound(String) |
| 105 | + case unreadableQueryFile(URL, Error?) |
| 106 | + |
| 107 | + public var description: String { |
| 108 | + switch self { |
| 109 | + case .graphQLErrors(let errors): |
| 110 | + return "GraphQL errors: \(errors.map(\.message).joined(separator: " | "))" |
| 111 | + case .missingData: |
| 112 | + return "Missing `data` in GraphQL response" |
| 113 | + case .decoding(let error): |
| 114 | + return "Decoding error: \(error)" |
| 115 | + case .queryFileNotFound(let name): |
| 116 | + return "GraphQL file '\(name)' not found in bundle" |
| 117 | + case .unreadableQueryFile(let url, let err): |
| 118 | + return "Could not read GraphQL file at \(url). \(err?.localizedDescription ?? "")" |
| 119 | + } |
| 120 | + } |
| 121 | +} |
| 122 | + |
| 123 | +public struct GraphQLError: Decodable { |
| 124 | + public let message: String |
| 125 | +} |
| 126 | + |
| 127 | +public struct GraphQLEmptyData: Decodable {} |
| 128 | + |
| 129 | +extension GraphQLClient { |
| 130 | + public func executeIgnoringData<Variables: Encodable>( |
| 131 | + query: String, |
| 132 | + variables: Variables? = nil, |
| 133 | + operationName: String? = nil, |
| 134 | + headers: [String: String] = [:] |
| 135 | + ) async throws { |
| 136 | + // Reuse EmptyData so decoding still works with `{ "data": null }` or `{ "data": {} }` |
| 137 | + _ = try await execute( |
| 138 | + query: query, |
| 139 | + variables: variables, |
| 140 | + operationName: operationName, |
| 141 | + headers: headers |
| 142 | + ) as GraphQLEmptyData |
| 143 | + } |
| 144 | + |
| 145 | + public func executeFromFileIgnoringData<Variables: Encodable>( |
| 146 | + resource: String, |
| 147 | + ext: String = "graphql", |
| 148 | + bundle: Bundle = .main, |
| 149 | + variables: Variables? = nil, |
| 150 | + operationName: String? = nil, |
| 151 | + headers: [String: String] = [:] |
| 152 | + ) async throws { |
| 153 | + _ = try await executeFromFile( |
| 154 | + resource: resource, |
| 155 | + ext: ext, |
| 156 | + bundle: bundle, |
| 157 | + variables: variables, |
| 158 | + operationName: operationName, |
| 159 | + headers: headers |
| 160 | + ) as GraphQLEmptyData |
| 161 | + } |
| 162 | +} |
0 commit comments