Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XKit / DeveloperServices / OpenAPI / LoggingMiddleware.swift

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