forked from apple/swift-http-api-proposal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTTPClient+Conveniences.swift
More file actions
224 lines (215 loc) · 10.3 KB
/
Copy pathHTTPClient+Conveniences.swift
File metadata and controls
224 lines (215 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP API Proposal open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift HTTP API Proposal project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
public import struct FoundationEssentials.URL
public import struct FoundationEssentials.Data
#else
public import struct Foundation.URL
public import struct Foundation.Data
#endif
@available(anyAppleOS 26.0, *)
extension HTTPClient
where
Self: ~Copyable & ~Escapable,
ResponseConcludingReader: ~Copyable,
ResponseConcludingReader.Underlying: ~Copyable,
RequestWriter: ~Copyable
{
/// Performs an HTTP request and processes the response.
///
/// This convenience method provides default values for `body` and `options` arguments,
/// making it easier to execute HTTP requests without specifying optional parameters.
///
/// - Parameters:
/// - request: The HTTP request header to send.
/// - body: The optional request body to send. Defaults to no body.
/// - options: The options for this request. Defaults to an empty initialized options.
/// - responseHandler: A closure that processes the response. The method invokes this
/// closure when it receives the response header, providing access to the response body.
///
/// - Returns: The value returned by the response handler closure.
///
/// - Throws: An error if the request fails or if the response handler throws.
public mutating func perform<Return: ~Copyable>(
request: HTTPRequest,
body: consuming HTTPClientRequestBody<RequestWriter>? = nil,
options: RequestOptions? = nil,
responseHandler: (HTTPResponse, consuming ResponseConcludingReader) async throws -> Return,
) async throws -> Return {
let options = options ?? self.defaultRequestOptions
return try await self.perform(request: request, body: body, options: options, responseHandler: responseHandler)
}
/// Performs an HTTP GET request and collects the response body.
///
/// This convenience method executes a GET request to the specified URL and collects
/// the response body data up to the specified limit.
///
/// - Parameters:
/// - url: The URL to send the GET request to.
/// - headerFields: The HTTP header fields to include in the request. Defaults to an empty collection.
/// - options: The options for this request. Defaults to an empty initialized options.
/// - limit: The maximum number of bytes to collect from the response body.
///
/// - Returns: A tuple containing the HTTP response header and the collected response body data.
///
/// - Throws: An error if the request fails, if the response body exceeds the limit, or if collection fails.
public mutating func get(
url: URL,
headerFields: HTTPFields = [:],
options: RequestOptions? = nil,
collectUpTo limit: Int,
) async throws -> (response: HTTPResponse, bodyData: Data) {
let request = HTTPRequest(url: url, headerFields: headerFields)
let options = options ?? self.defaultRequestOptions
return try await self.perform(request: request, body: nil, options: options) { response, body in
(
response,
try await Self.collectBody(body, upTo: limit)
)
}
}
/// Performs an HTTP POST request with a body and collects the response body.
///
/// This convenience method executes a POST request to the specified URL with the provided
/// request body data and collects the response body data up to the specified limit.
///
/// - Parameters:
/// - url: The URL to send the POST request to.
/// - headerFields: The HTTP header fields to include in the request. Defaults to an empty collection.
/// - bodyData: The request body data to send.
/// - options: The options for this request. Defaults to an empty initialized options.
/// - limit: The maximum number of bytes to collect from the response body.
///
/// - Returns: A tuple containing the HTTP response header and the collected response body data.
///
/// - Throws: An error if the request fails, if the response body exceeds the limit, or if collection fails.
public mutating func post(
url: URL,
headerFields: HTTPFields = [:],
bodyData: Data,
options: RequestOptions? = nil,
collectUpTo limit: Int,
) async throws -> (response: HTTPResponse, bodyData: Data) {
let request = HTTPRequest(method: .post, url: url, headerFields: headerFields)
let options = options ?? self.defaultRequestOptions
return try await self.perform(request: request, body: .data(bodyData), options: options) { response, body in
(
response,
try await Self.collectBody(body, upTo: limit)
)
}
}
/// Performs an HTTP PUT request with a body and collects the response body.
///
/// This convenience method executes a PUT request to the specified URL with the provided
/// request body data and collects the response body data up to the specified limit.
///
/// - Parameters:
/// - url: The URL to send the PUT request to.
/// - headerFields: The HTTP header fields to include in the request. Defaults to an empty collection.
/// - bodyData: The request body data to send.
/// - options: The options for this request. Defaults to an empty initialized options.
/// - limit: The maximum number of bytes to collect from the response body.
///
/// - Returns: A tuple containing the HTTP response header and the collected response body data.
///
/// - Throws: An error if the request fails, if the response body exceeds the limit, or if collection fails.
public mutating func put(
url: URL,
headerFields: HTTPFields = [:],
bodyData: Data,
options: RequestOptions? = nil,
collectUpTo limit: Int,
) async throws -> (response: HTTPResponse, bodyData: Data) {
let request = HTTPRequest(method: .put, url: url, headerFields: headerFields)
let options = options ?? self.defaultRequestOptions
return try await self.perform(request: request, body: .data(bodyData), options: options) { response, body in
(
response,
try await Self.collectBody(body, upTo: limit)
)
}
}
/// Performs an HTTP DELETE request and collects the response body.
///
/// This convenience method executes a DELETE request to the specified URL with an optional
/// request body and collects the response body data up to the specified limit.
///
/// - Parameters:
/// - url: The URL to send the DELETE request to.
/// - headerFields: The HTTP header fields to include in the request. Defaults to an empty collection.
/// - bodyData: The optional request body data to send. Defaults to no body.
/// - options: The options for this request. Defaults to an empty initialized options.
/// - limit: The maximum number of bytes to collect from the response body.
///
/// - Returns: A tuple containing the HTTP response header and the collected response body data.
///
/// - Throws: An error if the request fails, if the response body exceeds the limit, or if collection fails.
public mutating func delete(
url: URL,
headerFields: HTTPFields = [:],
bodyData: Data? = nil,
options: RequestOptions? = nil,
collectUpTo limit: Int,
) async throws -> (response: HTTPResponse, bodyData: Data) {
let request = HTTPRequest(method: .delete, url: url, headerFields: headerFields)
let options = options ?? self.defaultRequestOptions
return try await self.perform(request: request, body: bodyData.map { .data($0) }, options: options) { response, body in
(
response,
try await Self.collectBody(body, upTo: limit)
)
}
}
/// Performs an HTTP PATCH request with a body and collects the response body.
///
/// This convenience method executes a PATCH request to the specified URL with the provided
/// request body data and collects the response body data up to the specified limit.
///
/// - Parameters:
/// - url: The URL to send the PATCH request to.
/// - headerFields: The HTTP header fields to include in the request. Defaults to an empty collection.
/// - bodyData: The request body data to send.
/// - options: The options for this request. Defaults to an empty initialized options.
/// - limit: The maximum number of bytes to collect from the response body.
///
/// - Returns: A tuple containing the HTTP response header and the collected response body data.
///
/// - Throws: An error if the request fails, if the response body exceeds the limit, or if collection fails.
public mutating func patch(
url: URL,
headerFields: HTTPFields = [:],
bodyData: Data,
options: RequestOptions? = nil,
collectUpTo limit: Int,
) async throws -> (response: HTTPResponse, bodyData: Data) {
let request = HTTPRequest(method: .patch, url: url, headerFields: headerFields)
let options = options ?? self.defaultRequestOptions
return try await self.perform(request: request, body: .data(bodyData), options: options) { response, body in
(
response,
try await Self.collectBody(body, upTo: limit)
)
}
}
private static func collectBody<Reader: ConcludingAsyncReader>(_ body: consuming Reader, upTo limit: Int) async throws -> Data
where Reader: ~Copyable, Reader.Underlying: ~Copyable, Reader.Underlying.ReadElement == UInt8 {
try await body.collect(upTo: limit == .max ? .max : limit + 1) {
if $0.count > limit {
throw LengthLimitExceededError()
}
return $0.span.withUnsafeBytes { unsafe Data($0) }
}.0
}
}
struct LengthLimitExceededError: Error {}