Skip to content

Commit e8c5a2e

Browse files
committed
style: Format code
1 parent 499c487 commit e8c5a2e

30 files changed

Lines changed: 289 additions & 205 deletions

Demo.playground/Pages/Advanced.xcplaygroundpage/Contents.swift

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,17 @@ import Foundation
66

77
import APIWrapper
88

9-
/*:
10-
The `RaAPIWrapper` is extremely extensible.
11-
You can work with the `userInfo` property to customize the api parameters you need.
12-
13-
The `RaAPIWrapper/AF` module then takes advantage of this feature and supports the `ParameterEncoding` field of `Alamofire`.
14-
15-
The following code demonstrates how to add a custom parameter to `API`:
16-
*/
17-
18-
// will be used later as a custom parameter of the api.
9+
// MARK: - VerificationType
10+
11+
/// :
12+
/// The `RaAPIWrapper` is extremely extensible.
13+
/// You can work with the `userInfo` property to customize the api parameters you need.
14+
///
15+
/// The `RaAPIWrapper/AF` module then takes advantage of this feature and supports the `ParameterEncoding` field of `Alamofire`.
16+
///
17+
/// The following code demonstrates how to add a custom parameter to `API`:
18+
19+
/// will be used later as a custom parameter of the api.
1920
enum VerificationType: Hashable {
2021
case normal
2122
case special
@@ -35,12 +36,13 @@ extension API {
3536
}
3637
}
3738

39+
// MARK: - AdvancedAPI
40+
3841
enum AdvancedAPI {
3942
/// Finally, the new initialization method declared above is called on
4043
/// the property wrapper to complete the interface definition.
4144
@GET("/api", verification: .normal)
4245
static var testAPI: APIParameterBuilder<()>? = nil
4346
}
4447

45-
4648
//: [Next](@next)

Demo.playground/Pages/Basic.xcplaygroundpage/Contents.swift

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,12 @@ import Foundation
44

55
import APIWrapper
66

7-
/*:
8-
This example uses [Postman Echo](https://www.postman.com/postman/workspace/published-postman-templates/documentation/631643-f695cab7-6878-eb55-7943-ad88e1ccfd65?ctx=documentation) as the sample api.
9-
10-
The return value of this api depends on the parameters and will return the parameters, headers and other data as is.
11-
*/
7+
// MARK: - BasicAPI
8+
9+
/// :
10+
/// This example uses [Postman Echo](https://www.postman.com/postman/workspace/published-postman-templates/documentation/631643-f695cab7-6878-eb55-7943-ad88e1ccfd65?ctx=documentation) as the sample api.
11+
///
12+
/// The return value of this api depends on the parameters and will return the parameters, headers and other data as is.
1213

1314
//: To begin by showing some of the most basic uses, look at how the api is defined.
1415

@@ -26,12 +27,12 @@ enum BasicAPI {
2627
do {
2728
// Requests the api and parses the return value of the interface. Note the use of the `$` character.
2829
let response = try await BasicAPI.$get.request(to: PostManResponse<Arg>.self)
29-
30+
3031
// You can also ignore the return value and focus only on the act of requesting the api itself.
3132
try await BasicAPI.$get.request()
32-
33+
3334
} catch {
34-
print("❌ get request failure: \(error)")
35+
Log.log("❌ get request failure: \(error)")
3536
}
3637

3738
//: The api with parameters is a little more complicated to define:
@@ -45,10 +46,10 @@ extension BasicAPI {
4546
static var postWithTuple: APIParameterBuilder<(foo1: String, foo2: Int?)>? = .init {
4647
[
4748
"foo1": $0.foo1,
48-
"foo2": $0.foo2
49+
"foo2": $0.foo2,
4950
]
5051
}
51-
52+
5253
/// This is an api for requests using the **POST** method.
5354
///
5455
/// The full api address is: [](https://postman-echo.com/post) .
@@ -59,18 +60,19 @@ extension BasicAPI {
5960

6061
do {
6162
// Request the api and parse the return value.
62-
let tupleAPIResponse = try await BasicAPI.$postWithTuple.request(with: (foo1: "foo1", foo2: nil), to: PostManResponse<Arg>.self)
63-
64-
/**
65-
* If you look at the return value, you will see that `foo2` is not passed to the server.
66-
* This is because `RaAPIWrapper` filters out all parameters with the value `nil`.
67-
*/
68-
63+
let tupleAPIResponse = try await BasicAPI.$postWithTuple.request(
64+
with: (foo1: "foo1", foo2: nil),
65+
to: PostManResponse<Arg>.self
66+
)
67+
68+
/// If you look at the return value, you will see that `foo2` is not passed to the server.
69+
/// This is because `RaAPIWrapper` filters out all parameters with the value `nil`.
70+
6971
// Try using model as a parameter and you will get the same result.
7072
let modelAPIResponse = try await BasicAPI.$postWithModel.request(with: .init(foo2: "foo2"), to: PostManResponse<Arg>.self)
71-
73+
7274
} catch {
73-
print("❌ post request failure: \(error)")
75+
Log.log("❌ post request failure: \(error)")
7476
}
7577

7678
//: [Next](@next)

Demo.playground/Pages/Combine.xcplaygroundpage/Contents.swift

Lines changed: 43 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,17 @@ import ObjectiveC
88

99
import APIWrapper
1010

11-
/*:
12-
The design goal of `RaAPIWrapper` is to better encapsulate requests and simplify the request process rather than execute them.
13-
14-
So we don't provide any methods for request api. You can define your own request methods by referring to the code in the `Demo/Sources/API+Request.swift` file.
15-
16-
Here are 2 request wrappers for `Combine`, which are roughly written for reference only:
17-
*/
18-
19-
// For subsequent examples
11+
// MARK: - CombineAPI
12+
13+
/// :
14+
/// The design goal of `RaAPIWrapper` is to better encapsulate requests and simplify the request process rather than execute them.
15+
///
16+
/// So we don't provide any methods for request api.
17+
/// You can define your own request methods by referring to the code in the `Demo/Sources/API+Request.swift` file.
18+
///
19+
/// Here are 2 request wrappers for `Combine`, which are roughly written for reference only:
20+
21+
/// For subsequent examples
2022
enum CombineAPI {
2123
@POST("/post")
2224
static var post: APIParameterBuilder<String>? = { $0 }
@@ -29,54 +31,54 @@ enum CombineAPI {
2931
extension API {
3032
func requestPublisher(with params: Parameter) -> AnyPublisher<Data, URLError> {
3133
let info = createRequestInfo(params)
32-
34+
3335
// To simplify the demo process, here is a forced unpacking
34-
let url = URL(string: "https://postman-echo.com" + info.path)!
35-
36+
guard let url = URL(string: "https://postman-echo.com" + info.path) else {
37+
fatalError("url(\(info.path) nil!")
38+
}
39+
3640
var request = URLRequest(url: url)
3741
request.httpMethod = info.httpMethod.rawValue
38-
42+
3943
if let parameters = info.parameters {
4044
do {
4145
request.httpBody = try JSONEncoder().encode(parameters)
4246
} catch {
43-
fatalError("")
47+
fatalError("Encoder failure: \(error)")
4448
}
45-
49+
4650
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
4751
}
48-
52+
4953
return URLSession.shared
5054
.dataTaskPublisher(for: request)
51-
.map { (data, _) in return data }
55+
.map { data, _ in data }
5256
.mapError { $0 }
5357
.eraseToAnyPublisher()
5458
}
5559
}
5660

5761
var cancellable = Set<AnyCancellable>()
5862
let publisher = CombineAPI.$post.requestPublisher(with: "123")
59-
publisher.sink(receiveCompletion: {
60-
print($0)
61-
62-
}, receiveValue: {
63-
print(String(data: $0, encoding: .utf8) as Any)
64-
65-
}).store(in: &cancellable)
63+
publisher
64+
.sink(
65+
receiveCompletion: { Log.log($0) },
66+
receiveValue: { Log.log(String(data: $0, encoding: .utf8) as Any) }
67+
)
68+
.store(in: &cancellable)
6669

6770
// MARK: - PassthroughSubject
6871

69-
/*:
70-
The second one is to provide a `PassthroughSubject` object to the outside world,
71-
send parameters when requesting the api, subscribe to the object at other places,
72-
accept the parameters and send the request.
73-
*/
72+
/// :
73+
/// The second one is to provide a `PassthroughSubject` object to the outside world,
74+
/// send parameters when requesting the api, subscribe to the object at other places,
75+
/// accept the parameters and send the request.
7476

75-
private var kParamSubjectKey: String = "kParamSubjectKey"
77+
private var kParamSubjectKey = "kParamSubjectKey"
7678

77-
public extension API {
79+
extension API {
7880
@available(iOS 13.0, *)
79-
var paramSubject: PassthroughSubject<Parameter, URLError>? {
81+
public var paramSubject: PassthroughSubject<Parameter, URLError>? {
8082
get {
8183
if let value = objc_getAssociatedObject(self, &kParamSubjectKey) as? PassthroughSubject<Parameter, URLError> {
8284
return value
@@ -87,22 +89,21 @@ public extension API {
8789
}
8890
set { objc_setAssociatedObject(self, &kParamSubjectKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
8991
}
90-
92+
9193
@available(iOS 13.0, *)
92-
func requestPublisher() -> AnyPublisher<Data, URLError>? {
93-
return paramSubject?.flatMap { self.requestPublisher(with: $0) }.eraseToAnyPublisher()
94+
public func requestPublisher() -> AnyPublisher<Data, URLError>? {
95+
paramSubject?.flatMap { self.requestPublisher(with: $0) }.eraseToAnyPublisher()
9496
}
9597
}
9698

9799
let api = CombineAPI.$post
98100

99-
api.requestPublisher()?.sink(receiveCompletion: {
100-
print($0)
101-
102-
}, receiveValue: {
103-
print(String(data: $0, encoding: .utf8) as Any)
104-
105-
}).store(in: &cancellable)
101+
api.requestPublisher()?
102+
.sink(
103+
receiveCompletion: { Log.log($0) },
104+
receiveValue: { Log.log(String(data: $0, encoding: .utf8) as Any) }
105+
)
106+
.store(in: &cancellable)
106107

107108
api.paramSubject?.send("233")
108109
api.paramSubject?.send("433")

Demo.playground/Sources/API+Request.swift

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -10,73 +10,76 @@ import APIWrapper
1010
/// This part of the logic needs to be implemented by you in your own project,
1111
/// for now we provide a simple implementation:
1212

13-
public extension API {
13+
extension API {
1414
/// Request an api **with parameters** and resolve the api return value to a `T` type.
1515
///
1616
/// - Parameters:
1717
/// - params: api parameters.
1818
/// - type: the type of the api return value.
1919
/// - Returns: The result of the parsing.
20-
func request<T: Decodable>(with params: Parameter, to type: T.Type) async throws -> T {
20+
public func request<T: Decodable>(with params: Parameter, to type: T.Type) async throws -> T {
2121
let data = try await _request(with: params)
2222
return try JSONDecoder().decode(type, from: data)
2323
}
24-
24+
2525
/// Request an api **without** parameters.
2626
///
2727
/// This method means: the requesting party does not need the parameters returned by the api,
2828
/// so no return value is provided.
2929
///
3030
/// - Parameter params: api parameters.
31-
func request(with params: Parameter) async throws {
31+
public func request(with params: Parameter) async throws {
3232
_ = try await _request(with: params)
3333
}
3434
}
3535

3636
/// For some api that do not require parameters,
3737
/// we can also provide the following methods to make the request process even simpler.
3838

39-
public extension API where Parameter == Void {
39+
extension API where Parameter == Void {
4040
/// Request an api **without** parameters and resolve the api return value to a `T` type.
4141
///
4242
/// - Parameter type: The type of the api's return value.
4343
/// - Returns: The result of the parsing.
44-
func request<T: Decodable>(to type: T.Type) async throws -> T {
45-
return try await request(with: (), to: type)
44+
public func request<T: Decodable>(to type: T.Type) async throws -> T {
45+
try await request(with: (), to: type)
4646
}
47-
47+
4848
/// Request an api **without** parameters.
4949
///
5050
/// This method means: the requesting party does not need the parameters returned by the api,
5151
/// so no return value is provided.
52-
func request() async throws {
52+
public func request() async throws {
5353
try await request(with: ())
5454
}
5555
}
5656

5757
// MARK: - Tools
5858

59-
private extension API {
60-
func _request(with params: Parameter) async throws -> Data {
59+
extension API {
60+
private func _request(with params: Parameter) async throws -> Data {
6161
let info = createRequestInfo(params)
62-
62+
6363
// To simplify the demo process, here is a forced unpacking
64-
let url = URL(string: "https://postman-echo.com" + info.path)!
65-
print("▶️ Requests will begin soon: \(url.absoluteString)")
66-
64+
guard let url = URL(string: "https://postman-echo.com" + info.path) else {
65+
fatalError("url(\(info.path) nil!")
66+
}
67+
68+
Log.log("▶️ Requests will begin soon: \(url.absoluteString)")
69+
6770
var request = URLRequest(url: url)
6871
request.httpMethod = info.httpMethod.rawValue
69-
72+
7073
if let parameters = info.parameters {
71-
print("🚧 parameters: \(parameters)")
74+
Log.log("🚧 parameters: \(parameters)")
7275
request.httpBody = try JSONEncoder().encode(parameters)
73-
76+
7477
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
7578
}
76-
79+
7780
let (data, response) = try await URLSession.shared.data(for: request)
78-
print("\(response.url?.absoluteString ?? "nil") End of request")
79-
81+
Log.log("\(response.url?.absoluteString ?? "nil") End of request")
82+
8083
return data
8184
}
8285
}

Demo.playground/Sources/Log.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import Foundation
2+
3+
enum Log {
4+
static func log(_ content: Any) {
5+
// swiftlint:disable:next no_direct_standard_out_logs
6+
print(content)
7+
}
8+
}

0 commit comments

Comments
 (0)