Skip to content

Commit

Permalink
feat(http-client): introduce safe string convertible (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
portellaa authored Feb 7, 2023
1 parent 76b1ee6 commit fa6bfc4
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 5 deletions.
22 changes: 19 additions & 3 deletions Sources/YData/Client/InternalClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,12 @@ public extension InternalClient {
var scheme: URI.Scheme { URI.Scheme("http") }
var basePath: String? { nil }

func send<Request: InternalRequest, Response: InternalResponse>(_ request: Request) -> EventLoopFuture<Response> {
func send<Request, Response>(_ request: Request) -> EventLoopFuture<Response>
where Request: InternalRequest, Response: InternalResponse {
let clientRequest = buildClientRequest(for: request)

return httpClient.send(buildClientRequest(for: request))
.always { self.logger.info("response for request \(clientRequest.url): \($0)") }
return httpClient.send(clientRequest)
.always { self.logger.info("response for request \(clientRequest.url): \($0.safeDescription)") }
.mapToInternalResponse()
}

Expand Down Expand Up @@ -69,3 +70,18 @@ private extension EventLoopFuture where Value: InternalResponse {
}
}
}

extension Result: SafeStringConvertible {
public var safeDescription: String {
switch self {
case .failure(let error):
return "\(error)"
case .success(let value):
if let value = value as? SafeStringConvertible {
return value.safeDescription
}

return "\(value)"
}
}
}
2 changes: 2 additions & 0 deletions Sources/YData/Client/InternalResponse+Vapor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,5 @@ extension Internal.SuccessResponse: ResponseEncodable {
return request.eventLoop.makeSucceededFuture(response)
}
}

extension ClientResponse: SafeStringConvertible {}
8 changes: 6 additions & 2 deletions Sources/YData/Client/InternalResponse.swift
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,12 @@ public extension Internal.SuccessResponse {
}
}

public extension CustomStringConvertible where Self: InternalResponse {
var description: String {
public protocol SafeStringConvertible {
var safeDescription: String { get }
}

public extension SafeStringConvertible where Self: InternalResponse {
var safeDescription: String {
var desc = ["HTTP/1.1 \(status.code) \(status.reasonPhrase)"]
desc += self.headers.map { "\($0.name): \($0.value)" }
return desc.joined(separator: "\n")
Expand Down

0 comments on commit fa6bfc4

Please sign in to comment.