2020-07-29 23:50:30 +00:00
|
|
|
// Copyright © 2020 Metabolist. All rights reserved.
|
|
|
|
|
2020-09-05 02:31:43 +00:00
|
|
|
import Foundation
|
2020-07-29 23:50:30 +00:00
|
|
|
|
2020-09-23 07:04:37 +00:00
|
|
|
public protocol Target {
|
2020-07-29 23:50:30 +00:00
|
|
|
var baseURL: URL { get }
|
|
|
|
var pathComponents: [String] { get }
|
|
|
|
var method: HTTPMethod { get }
|
2020-10-27 03:01:12 +00:00
|
|
|
var queryParameters: [URLQueryItem] { get }
|
2020-09-23 07:04:37 +00:00
|
|
|
var jsonBody: [String: Any]? { get }
|
2020-12-16 01:39:38 +00:00
|
|
|
var multipartFormData: [String: MultipartFormValue]? { get }
|
2020-09-23 07:04:37 +00:00
|
|
|
var headers: [String: String]? { get }
|
2020-07-29 23:50:30 +00:00
|
|
|
}
|
|
|
|
|
2020-08-31 01:40:58 +00:00
|
|
|
public extension Target {
|
2020-09-23 07:04:37 +00:00
|
|
|
func urlRequest() -> URLRequest {
|
2020-07-29 23:50:30 +00:00
|
|
|
var url = baseURL
|
|
|
|
|
|
|
|
for pathComponent in pathComponents {
|
|
|
|
url.appendPathComponent(pathComponent)
|
|
|
|
}
|
|
|
|
|
2020-10-27 03:01:12 +00:00
|
|
|
if var components = URLComponents(url: url, resolvingAgainstBaseURL: true), !queryParameters.isEmpty {
|
|
|
|
components.queryItems = queryParameters
|
2020-09-23 07:04:37 +00:00
|
|
|
|
|
|
|
if let queryComponentURL = components.url {
|
|
|
|
url = queryComponentURL
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var urlRequest = URLRequest(url: url)
|
|
|
|
|
|
|
|
urlRequest.httpMethod = method.rawValue
|
|
|
|
urlRequest.allHTTPHeaderFields = headers
|
|
|
|
|
|
|
|
if let jsonBody = jsonBody {
|
|
|
|
urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: jsonBody)
|
2020-09-24 01:33:13 +00:00
|
|
|
urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
|
2020-12-16 01:39:38 +00:00
|
|
|
} else if let multipartFormData = multipartFormData {
|
|
|
|
let boundary = "Boundary-\(UUID().uuidString)"
|
|
|
|
var httpBody = Data()
|
|
|
|
|
|
|
|
for (key, value) in multipartFormData {
|
|
|
|
httpBody.append(value.httpBodyComponent(boundary: boundary, key: key))
|
|
|
|
}
|
|
|
|
|
|
|
|
httpBody.append(Data("--\(boundary)--".utf8))
|
|
|
|
urlRequest.httpBody = httpBody
|
|
|
|
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
|
2020-09-23 07:04:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return urlRequest
|
2020-07-29 23:50:30 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-08-31 01:40:58 +00:00
|
|
|
public protocol DecodableTarget: Target {
|
2020-07-29 23:50:30 +00:00
|
|
|
associatedtype ResultType: Decodable
|
|
|
|
}
|
2020-08-31 01:40:58 +00:00
|
|
|
|
|
|
|
public protocol TargetProcessing {
|
|
|
|
static func process(target: Target)
|
|
|
|
}
|