Skip to content

armgit / xtool

Public Imported from GitHub
0

Cross-platform Xcode replacement. Build and deploy iOS apps with SwiftPM on Linux, Windows, macOS.

1.3 KB
Raw Blame
import XUtils
import Foundation
import OpenAPIRuntime
import HTTPTypes

struct LoggingMiddleware: ClientMiddleware {
    static let regex: NSRegularExpression? = {
        guard let pat = ProcessInfo.processInfo.environment["XTL_DEV_LOG"] else { return nil }
        return try? NSRegularExpression(pattern: pat)
    }()

    func intercept(
        _ request: HTTPRequest,
        body: HTTPBody?,
        baseURL: URL,
        operationID: String,
        next: (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?)
    ) async throws -> (HTTPResponse, HTTPBody?) {
        var (response, body) = try await next(request, body, baseURL)

        guard Self.regex?.firstMatch(
                  in: operationID,
                  range: NSRange(operationID.startIndex..., in: operationID)
              ) != nil
              else { return (response, body) }

        d.out.print("\n\(operationID) response status -> \(response.status)")

        if let unwrapped = body {
            let data = try await Data(collecting: unwrapped, upTo: .max)
            // body may only be consumable once, replace it with the collected data
            body = .init(data)

            let text = String(decoding: data, as: UTF8.self)
            d.out.print("\(operationID) response body -> \(text)")
        }

        return (response, body)
    }
}