Skip to content

Add async/await support #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions Sources/Request/Request/Request.swift
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,40 @@ public struct AnyRequest<ResponseType> where ResponseType: Decodable {
.subscribe(UpdateSubscriber(request: self))
}
}

#if swift(>=5.5)
/// Performs the `Request`, then returns the `ResponseType` or throws.
public func call() async throws -> ResponseType {
let publisher = self.buildPublisher()

return try await withCheckedThrowingContinuation { continuation in
var cancellable: AnyCancellable?
cancellable = publisher.sink { completion in
switch completion {
case .finished:
break
case let .failure(error):
continuation.resume(throwing: error)
}
cancellable?.cancel()
} receiveValue: { value in
do {
if ResponseType.self == Data.self {
continuation.resume(returning: value.data as! ResponseType)
} else {
continuation.resume(returning: try JSONDecoder().decode(ResponseType.self, from: value.data))
}
} catch {
continuation.resume(throwing: error)
}
}
}
}

public func callAsFunction() async throws -> ResponseType {
return try await call()
}
#endif

internal func buildSession() -> (configuration: URLSessionConfiguration, request: URLRequest) {
var request = URLRequest(url: URL(string: "https://")!)
Expand Down
4 changes: 4 additions & 0 deletions Sources/Request/Request/RequestBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,8 @@ public struct RequestBuilder {
public static func buildEither(second: RequestParam) -> RequestParam {
second
}

public static func buildArray(_ components: [RequestParam]) -> RequestParam {
CombinedParams(children: components)
}
}
2 changes: 1 addition & 1 deletion Sources/Request/Request/RequestParams/CombinedParams.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ internal struct CombinedParams: RequestParam, SessionParam {

func buildParam(_ request: inout URLRequest) {
children
.sorted { a, _ in (a is Url) }
.sorted { a, _ in (a is Url) || (a is Foundation.URL) }
.filter { !($0 is SessionParam) || $0 is CombinedParams }
.forEach {
$0.buildParam(&request)
Expand Down
2 changes: 2 additions & 0 deletions Sources/Request/Request/RequestParams/EmptyParam.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import Foundation

public struct EmptyParam: RequestParam {
public init() {}

public func buildParam(_ request: inout URLRequest) {}
}

Expand Down
12 changes: 11 additions & 1 deletion Sources/Request/Request/RequestParams/Header.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,17 @@
import Foundation

/// Creates a `HeaderParam` for any number of different headers
public struct Header {
public struct Header: RequestParam {
private let _backing: `Any`

public init(key: String, value: String) {
self._backing = .init(key: key, value: value)
}

public func buildParam(_ request: inout URLRequest) {
_backing.buildParam(&request)
}

/// Sets the value for any header
public struct `Any`: RequestParam {
private let key: String
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import Foundation

extension Foundation.URL: RequestParam {
public func buildParam(_ request: inout URLRequest) {
request.url = self
}
}
8 changes: 1 addition & 7 deletions Tests/LinuxMain.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1 @@
import XCTest

import RequestTests

var tests = [XCTestCaseEntry]()
tests += RequestTests.allTests()
XCTMain(tests)
fatalError("Test with the `--enable-test-discovery` flag.")
67 changes: 46 additions & 21 deletions Tests/RequestTests/RequestTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ final class RequestTests: XCTestCase {
Url("https://jsonplaceholder.typicode.com/todos")
})
}

func testFoundationURL() {
performRequest(Request {
URL(string: "https://jsonplaceholder.typicode.com/todos")!
})
}

func testRequestWithCondition() {
let condition = true
Expand Down Expand Up @@ -120,6 +126,16 @@ final class RequestTests: XCTestCase {
Query([QueryParam("key", value: "value"), QueryParam("key2", value: "value2")])
})
}

func testBuildArray() {
let headers = ["Content-Type": "application/json", "Cache-Control": "no-cache"]
performRequest(Request {
Url("https://jsonplaceholder.typicode.com/todos")
for (key, value) in headers {
Header(key: key, value: value)
}
})
}

func testComplexRequest() {
performRequest(Request {
Expand Down Expand Up @@ -701,26 +717,35 @@ final class RequestTests: XCTestCase {

waitForExpectations(timeout: 10000)
}

static var allTests = [
("simpleRequest", testSimpleRequest),
("post", testPost),
("query", testQuery),
("complexRequest", testComplexRequest),
("headers", testHeaders),
("onObject", testObject),
("onStatusCode", testStatusCode),
("onString", testString),
("onJson", testJson),
("requestGroup", testRequestGroup),
("requestChain", testRequestChain),
("requestChainErrors", testRequestChainErrors),
("anyRequest", testAnyRequest),
("testError", testError),
("testUpdate", testUpdate),

#if swift(>=5.5)
struct Todo: Decodable, Hashable {
let id: Int
let userId: Int
let title: String
let completed: Bool
}

func testAsync() async throws {

let getTodos = AnyRequest<[Todo]> {
Url("https://jsonplaceholder.typicode.com/todos")
}

// Test out `async let`, `try await`, and `callAsFunction`.
async let callTodos = getTodos.call()
async let callAsFunctionTodos = getTodos()
let calledTodos = try await callTodos
let calledAsFunctionTodos = try await callAsFunctionTodos
XCTAssertEqual(calledTodos, calledAsFunctionTodos)
}

func testCallAsFunction() async throws {
let request = Request {
Url("https://jsonplaceholder.typicode.com/todos")
}

("testPublisher", testPublisher),
("testPublisherDecode", testPublisherDecode),
("testPublisherGroup", testPublisherGroup)
]
let _ = try await request()
}
#endif
}
10 changes: 0 additions & 10 deletions Tests/RequestTests/XCTestManifests.swift

This file was deleted.