Skip to content

Commit

Permalink
save responses and subscriptions
Browse files Browse the repository at this point in the history
  • Loading branch information
terhechte committed Dec 16, 2022
1 parent a2f05c5 commit 306e627
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 7 deletions.
31 changes: 30 additions & 1 deletion Sources/SwiftGraphQL/HTTP+WebSockets.swift
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public class GraphQLSocket<S: GraphQLEnabledSocket> {
// log: OSLog.subscription,
// type: .debug, (String(data: data, encoding: .utf8) ?? "Invalid .utf8")
// )
guard let message = try? JSONDecoder().decode(Message.self, from: data) else {
guard var message = try? JSONDecoder().decode(Message.self, from: data) else {
os_log("Invalid JSON Payload", log: OSLog.subscription, type: .debug)
return false
}
Expand Down Expand Up @@ -130,6 +130,7 @@ public class GraphQLSocket<S: GraphQLEnabledSocket> {
self?.state = .running
case .next, .error, .complete, .data:
guard let id = message.id else { return false }
message.originalData = data
self?.subscriptions[id]?(message)
case .connection_terminate, .connection_error:
self?.restart(errorHandler: errorHandler)
Expand Down Expand Up @@ -220,6 +221,21 @@ public class GraphQLSocket<S: GraphQLEnabledSocket> {
self?.complete(id: id)
}

#if DEBUG
#if targetEnvironment(simulator)
let payload = selection.buildPayload(operationName: operationName)

// Write the query. We also need the id, so we encode it into the variables
try? payload.query.write(toFile: "/tmp/query_\(id).graphql", atomically: true, encoding: .utf8)
// Write the variables
var copiedVariables = payload.variables
copiedVariables["gql-subscription-id"] = AnyCodable(stringLiteral: id)
if let variables = try? encoder.encode(copiedVariables) {
try? variables.write(to: URL(fileURLWithPath: "/tmp/query_variables_\(id).json"))
}
#endif
#endif

switch state {
case .notRunning:
if autoConnect {
Expand Down Expand Up @@ -260,6 +276,17 @@ public class GraphQLSocket<S: GraphQLEnabledSocket> {
switch message.type {
case .next, .data:
do {
if let originalData = message.originalData {

#if DEBUG
#if targetEnvironment(simulator)
// write the response out. A given subscription can have multiple responses.
let debugTime = DispatchTime.now().uptimeNanoseconds
let url = URL(fileURLWithPath: "/tmp/subscription_response_\(id)_\(debugTime).json")
try? originalData.write(to: url)
#endif
#endif
}
let result = try GraphQLResult(webSocketMessage: message, with: selection)
eventHandler(.success(result))
} catch {
Expand Down Expand Up @@ -339,6 +366,8 @@ public struct GraphQLSocketMessage: Codable {
case pong
}

public var originalData: Data?

public var type: MessageType
public var id: String?
/// Used for retreiving payload after decoding incomming message
Expand Down
33 changes: 27 additions & 6 deletions Sources/SwiftGraphQL/HTTP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,17 +89,39 @@ private func send<Type, TypeLock>(
return nil
}

let debugTime = DispatchTime.now().uptimeNanoseconds

// Construct a GraphQL request.
let request = createGraphQLRequest(
selection: selection,
operationName: operationName,
url: url,
headers: headers,
method: method
method: method,
debugTime: debugTime
)

// Create a completion handler.
func onComplete(data: Data?, response: URLResponse?, error: Error?) {

// Save the response or the error, depending on what's available
#if DEBUG
#if targetEnvironment(simulator)
let fallback = "\(String(describing: response))".data(using: .utf8) ?? "{'error': 'Could not serialize response'}".data(using: .utf8)!
let responeData: Data
if let data = data {
responeData = data
} else if let error = error {
responeData = "{'error': '\(error.localizedDescription)'}".data(using: .utf8)
?? fallback
} else {
responeData = fallback
}
let url = URL(fileURLWithPath: "/tmp/query_response_\(debugTime).json")
try? responeData.write(to: url)
#endif
#endif

/* Process the response. */
// Check for HTTP errors.
if let error = error {
Expand Down Expand Up @@ -197,7 +219,8 @@ private func createGraphQLRequest<Type, TypeLock>(
operationName: String?,
url: URL,
headers: HttpHeaders,
method: HttpMethod
method: HttpMethod,
debugTime: UInt64
) -> URLRequest where TypeLock: GraphQLOperation & Decodable {
// Construct a request.
var request = URLRequest(url: url)
Expand All @@ -216,12 +239,10 @@ private func createGraphQLRequest<Type, TypeLock>(
#if DEBUG
#if targetEnvironment(simulator)
// Write the query
let time = DispatchTime.now().uptimeNanoseconds
let filename = operationName ?? "\(time)"
try? payload.query.write(toFile: "/tmp/query_\(filename).graphql", atomically: true, encoding: .utf8)
try? payload.query.write(toFile: "/tmp/query_\(debugTime).graphql", atomically: true, encoding: .utf8)
// Write the variables
if let variables = try? encoder.encode(payload.variables) {
try? variables.write(to: URL(fileURLWithPath: "/tmp/query_variables_\(filename).json"))
try? variables.write(to: URL(fileURLWithPath: "/tmp/query_variables_\(debugTime).json"))
}
#endif
#endif
Expand Down

0 comments on commit 306e627

Please sign in to comment.