xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XKit / DeveloperServices / OpenAPI / LoggingMiddleware.swift
LoggingMiddleware.swift39 lines · 1.3 KiBRaw
| 1 | import Foundation |
| 2 | import OpenAPIRuntime |
| 3 | import HTTPTypes |
| 4 | |
| 5 | struct LoggingMiddleware: ClientMiddleware { |
| 6 | static let regex: NSRegularExpression? = { |
| 7 | guard let pat = ProcessInfo.processInfo.environment["XTL_DEV_LOG"] else { return nil } |
| 8 | return try? NSRegularExpression(pattern: pat) |
| 9 | }() |
| 10 | |
| 11 | func intercept( |
| 12 | _ request: HTTPRequest, |
| 13 | body: HTTPBody?, |
| 14 | baseURL: URL, |
| 15 | operationID: String, |
| 16 | next: (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?) |
| 17 | ) async throws -> (HTTPResponse, HTTPBody?) { |
| 18 | var (response, body) = try await next(request, body, baseURL) |
| 19 | |
| 20 | guard Self.regex?.firstMatch( |
| 21 | in: operationID, |
| 22 | range: NSRange(operationID.startIndex..., in: operationID) |
| 23 | ) != nil |
| 24 | else { return (response, body) } |
| 25 | |
| 26 | print("\n\(operationID) response status -> \(response.status)") |
| 27 | |
| 28 | if let unwrapped = body { |
| 29 | let data = try await Data(collecting: unwrapped, upTo: .max) |
| 30 | // body may only be consumable once, replace it with the collected data |
| 31 | body = .init(data) |
| 32 | |
| 33 | let text = String(decoding: data, as: UTF8.self) |
| 34 | print("\(operationID) response body -> \(text)") |
| 35 | } |
| 36 | |
| 37 | return (response, body) |
| 38 | } |
| 39 | } |