|
| 1 | +import Foundation |
| 2 | + |
| 3 | +/// A GraphQL request object, containing `query`, `operationName`, and `variables` fields |
| 4 | +public struct GraphQLRequest: Equatable, Codable { |
| 5 | + public var query: String |
| 6 | + public var operationName: String? |
| 7 | + public var variables: [String: Map] |
| 8 | + |
| 9 | + public init(query: String, operationName: String? = nil, variables: [String: Map] = [:]) { |
| 10 | + self.query = query |
| 11 | + self.operationName = operationName |
| 12 | + self.variables = variables |
| 13 | + } |
| 14 | + |
| 15 | + // To handle decoding with a default of variables = [] |
| 16 | + public init(from decoder: Decoder) throws { |
| 17 | + let container = try decoder.container(keyedBy: CodingKeys.self) |
| 18 | + self.query = try container.decode(String.self, forKey: .query) |
| 19 | + self.operationName = try container.decodeIfPresent(String.self, forKey: .operationName) |
| 20 | + self.variables = try container.decodeIfPresent([String: Map].self, forKey: .variables) ?? [:] |
| 21 | + } |
| 22 | + |
| 23 | + /// Boolean indicating if the GraphQL request is a subscription operation. |
| 24 | + /// This operation performs an entire AST parse on the GraphQL request, so consider |
| 25 | + /// performance when calling multiple times. |
| 26 | + /// |
| 27 | + /// - Returns: True if request is a subscription, false if it is an atomic operation (like `query` or `mutation`) |
| 28 | + public func isSubscription() throws -> Bool { |
| 29 | + let documentAST = try GraphQL.parse( |
| 30 | + instrumentation: NoOpInstrumentation, |
| 31 | + source: Source(body: self.query, name: "GraphQL request") |
| 32 | + ) |
| 33 | + let firstOperation = documentAST.definitions.compactMap { $0 as? OperationDefinition }.first |
| 34 | + guard let operationType = firstOperation?.operation else { |
| 35 | + throw GraphQLError(message: "GraphQL operation type could not be determined") |
| 36 | + } |
| 37 | + return operationType == .subscription |
| 38 | + } |
| 39 | +} |
| 40 | + |
0 commit comments