Skip to content

Commit ad4f7ea

Browse files
committed
Some handy extensions to work with HTTPClientResponse body
1 parent fb308ee commit ad4f7ea

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

Sources/AsyncHTTPClient/AsyncAwait/HTTPClientResponse.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,19 @@ extension HTTPClientResponse {
138138
}
139139
}
140140

141+
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
142+
extension HTTPClientResponse {
143+
/// Response body as `ByteBuffer`.
144+
public var bytes: ByteBuffer {
145+
get async throws {
146+
let expectedBytes = headers
147+
.first(name: "content-length")
148+
.flatMap(Int.init) ?? 1024 * 1024
149+
return try await body.collect(upTo: expectedBytes)
150+
}
151+
}
152+
}
153+
141154
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
142155
@usableFromInline
143156
typealias TransactionBody = NIOThrowingAsyncSequenceProducer<

Sources/AsyncHTTPClient/FoundationExtensions.swift

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,14 @@ extension HTTPClient.Body {
6464
return self.bytes(data)
6565
}
6666
}
67+
68+
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
69+
extension HTTPClientResponse {
70+
/// Response body as `Data`.
71+
public var data: Data? {
72+
get async throws {
73+
var bytes = try await bytes
74+
return bytes.readData(length: bytes.readableBytes)
75+
}
76+
}
77+
}

0 commit comments

Comments
 (0)