[Swift5] Add an async execute API to RequestBuilder<T> (#14416)

* Add async `execute` interface

* Update samples

Run `./bin/generate-samples.sh`

* Add an explicit `self`

I forgot to add it

* Add an availability condition
This commit is contained in:
yosshi4486 2023-01-11 02:05:52 +09:00 committed by GitHub
parent c6ea564600
commit 4044e724c0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 0 deletions

View File

@ -65,6 +65,33 @@ import Vapor
return requestTask return requestTask
} }
{{#useAsyncAwait}}
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
@discardableResult
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute() async throws -> Response<T> {
return try await withTaskCancellationHandler {
try Task.checkCancellation()
return try await withCheckedThrowingContinuation { continuation in
guard !Task.isCancelled else {
continuation.resume(throwing: CancellationError())
return
}
self.execute { result in
switch result {
case let .success(response):
continuation.resume(returning: response)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
} onCancel: {
self.requestTask.cancel()
}
}
{{/useAsyncAwait}}
{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func addHeader(name: String, value: String) -> Self { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func addHeader(name: String, value: String) -> Self {
if !value.isEmpty { if !value.isEmpty {
headers[name] = value headers[name] = value

View File

@ -56,6 +56,31 @@ open class RequestBuilder<T> {
return requestTask return requestTask
} }
@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
@discardableResult
open func execute() async throws -> Response<T> {
return try await withTaskCancellationHandler {
try Task.checkCancellation()
return try await withCheckedThrowingContinuation { continuation in
guard !Task.isCancelled else {
continuation.resume(throwing: CancellationError())
return
}
self.execute { result in
switch result {
case let .success(response):
continuation.resume(returning: response)
case let .failure(error):
continuation.resume(throwing: error)
}
}
}
} onCancel: {
self.requestTask.cancel()
}
}
public func addHeader(name: String, value: String) -> Self { public func addHeader(name: String, value: String) -> Self {
if !value.isEmpty { if !value.isEmpty {
headers[name] = value headers[name] = value