Skip to content

Commit 283cc4d

Browse files
Merge pull request #97 from NeedleInAJayStack/fix/GraphQLRequest
Adds GraphQLRequest type
2 parents 151c2f1 + 239211c commit 283cc4d

File tree

2 files changed

+44
-4
lines changed

2 files changed

+44
-4
lines changed

Package.resolved

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,17 @@
66
"repositoryURL": "https://github.com/apple/swift-collections",
77
"state": {
88
"branch": null,
9-
"revision": "2d33a0ea89c961dcb2b3da2157963d9c0370347e",
10-
"version": "1.0.1"
9+
"revision": "48254824bb4248676bf7ce56014ff57b142b77eb",
10+
"version": "1.0.2"
1111
}
1212
},
1313
{
1414
"package": "swift-nio",
1515
"repositoryURL": "https://github.com/apple/swift-nio.git",
1616
"state": {
1717
"branch": null,
18-
"revision": "120acb15c39aa3217e9888e515de160378fbcc1e",
19-
"version": "2.18.0"
18+
"revision": "51c3fc2e4a0fcdf4a25089b288dd65b73df1b0ef",
19+
"version": "2.37.0"
2020
}
2121
}
2222
]

Sources/GraphQL/GraphQLRequest.swift

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
 (0)