-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEndpoint.swift
More file actions
175 lines (131 loc) · 5.41 KB
/
Endpoint.swift
File metadata and controls
175 lines (131 loc) · 5.41 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
//
// Endpoint.swift
// GoodNetworking
//
// Created by Filip Šašala on 10/12/2023.
//
import Foundation
// MARK: - Endpoint
/// `Endpoint` protocol defines a set of requirements for an endpoint.
public protocol Endpoint {
/// The path to be appended to the base URL.
var path: URLConvertible { get }
/// HTTP method to be used for the request.
var method: HTTPMethod { get }
/// Parameters to be sent with the request.
var parameters: EndpointParameters? { get }
/// HTTP headers to be added to the request.
var headers: HTTPHeaders? { get }
/// Encoding to be used for encoding the parameters.
@available(*, deprecated, message: "Encoding will be automatically determined by the kind of `parameters` in the future.")
var encoding: ParameterEncoding { get }
/// Creates a URL by resolving `path` over `baseUrl`.
///
/// This function is a customization point for modifying the URL by current runtime,
/// for example for API versioning or platform separation.
///
/// Note that this function will be only called if the ``path`` resolved
/// is a relative URL. If ``path`` specifies an absolute URL, it will be
/// used instead, without any modifications.
///
/// - Parameter baseUrl: Base URL for the request to combine with.
/// - Returns: URL for the request or `nil` if such URL cannot be constructed.
@NetworkActor func url(on baseUrl: URLConvertible) async -> URL?
}
public extension Endpoint {
@NetworkActor func url(on baseUrl: URLConvertible) async -> URL? {
let baseUrl = await baseUrl.resolveUrl()
let path = await path.resolveUrl()
guard let baseUrl, let path else { return nil }
// merge URLs as strings to avoid URL escaping
return URL(baseUrl.absoluteString + path.absoluteString)
}
}
@available(*, deprecated, message: "Default values for deprecated properties")
public extension Endpoint {
var encoding: ParameterEncoding { AutomaticEncoding.default }
}
// MARK: - Parameters
/// Enum that represents the data to be sent with the request,
/// either as a body or as query parameters.
public enum EndpointParameters {
/// Case for sending `Parameters`.
@available(*, deprecated, renamed: "json", message: "Use JSON instead of raw dictionaries")
case parameters([String: Any])
case query([URLQueryItem])
case model(Encodable)
case data(Data)
case json(JSON)
public var dictionary: JSON? {
switch self {
case .parameters(let dictionary):
return JSON(dictionary)
case .query(let queryItems):
assertionFailure("Handling URLQueryItems as JSON is not optimal.")
return JSON(queryItems
.map { ($0.name, JSON($0.value as Any)) }
.reduce(into: [:], { $0[$1.0] = $1.1 }))
case .model(let anyEncodable):
if let customEncodable = anyEncodable as? WithCustomEncoder {
let customEncoder = type(of: customEncodable).encoder
return JSON(encodable: anyEncodable, encoder: customEncoder)
} else {
return JSON(anyEncodable)
}
case .data(let data):
return try? JSON(data: data)
case .json(let json):
return json
}
}
internal func data() throws(NetworkError) -> Data? {
switch self {
case .parameters, .query:
return self.dictionary?.data()
case .model(let codableModel):
do {
let encoder = JSONEncoder()
return try encoder.encode(codableModel)
} catch {
throw URLError(.cannotEncodeRawData).asNetworkError()
}
case .data(let data):
return data
case .json(let json):
return json.data()
}
}
internal func queryItems() -> [URLQueryItem] {
if case .query(let queryItems) = self {
return queryItems
} else { // Handle `Encodable` query and legacy support
guard let json = self.dictionary else { return [] }
return json.dictionary?.map { key, value in URLQueryItem(name: key, value: "\(value)") } ?? []
}
}
}
// MARK: - Compatibility
@available(*, deprecated, message: "Encoding will be automatically determined by the kind of `parameters` in the future.")
public protocol ParameterEncoding {}
@available(*, deprecated, message: "Encoding will be automatically determined by the kind of `parameters` in the future.")
public enum URLEncoding: ParameterEncoding {
case `default`
}
@available(*, deprecated, message: "Encoding will be automatically determined by the kind of `parameters` in the future.")
public enum JSONEncoding: ParameterEncoding {
case `default`
}
@available(*, deprecated, message: "Encoding will be automatically determined by the kind of `parameters` in the future.")
public enum AutomaticEncoding: ParameterEncoding {
case `default`
}
@available(*, deprecated, message: "Use URLConvertible instead.")
public extension String {
@available(*, deprecated, message: "Use URLConvertible instead.")
func asURL() throws -> URL {
guard let url = URL(string: self) else {
throw URLError(.badURL).asNetworkError()
}
return url
}
}