Skip to content
This repository was archived by the owner on Sep 30, 2024. It is now read-only.

Commit f5b4640

Browse files
committed
Make some fields on JsonAPI protocol optional
1 parent 392a85d commit f5b4640

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Frameworks/Microya/Models/JsonApi.swift

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,35 @@ public enum JsonApiError: Error {
1515
case unknownError(Error)
1616
}
1717

18+
/// The protocol which defines the structure of an API endpoint.
1819
public protocol JsonApi {
20+
/// The JSON decoder to be used for decoding.
1921
var decoder: JSONDecoder { get }
22+
23+
/// The JSNO encoder to be used for encoding.
2024
var encoder: JSONEncoder { get }
2125

26+
/// The common base URL of the API endpoints.
2227
var baseUrl: URL { get }
28+
29+
/// The headers to be sent per request.
2330
var headers: [String: String] { get }
31+
32+
/// The subpath to be added to the base URL.
2433
var path: String { get }
34+
35+
/// The HTTP method to be used for the request.
2536
var method: Method { get }
37+
38+
/// The URL query parameters to be sent (part after ? in URLs, e.g. google.com?query=Harry+Potter).
2639
var queryParameters: [(key: String, value: String)] { get }
40+
41+
/// The body data to be sent along the request (e.g. JSON contents in a POST request).
2742
var bodyData: Data? { get }
2843
}
2944

3045
extension JsonApi {
46+
/// Performs the request. Make sure to specify the correct return type (e.g. let result: MyType = api.request...).
3147
public func request<ResultType: Decodable>(type: ResultType.Type) -> Result<ResultType, JsonApiError> {
3248
let dispatchGroup = DispatchGroup()
3349
dispatchGroup.enter()
@@ -93,3 +109,26 @@ extension JsonApi {
93109
return urlComponents.url!
94110
}
95111
}
112+
113+
/// Extension to provide default contents for optional fields.
114+
extension JsonApi {
115+
public var decoder: JSONDecoder {
116+
JSONDecoder()
117+
}
118+
119+
public var encoder: JSONEncoder {
120+
JSONEncoder()
121+
}
122+
123+
public var headers: [String: String] {
124+
[:]
125+
}
126+
127+
public var queryParameters: [(key: String, value: String)] {
128+
[]
129+
}
130+
131+
public var bodyData: Data? {
132+
nil
133+
}
134+
}

0 commit comments

Comments
 (0)