Created
January 17, 2023 14:38
-
-
Save dinotrnka/6dc8a14bc9d4e2b2c9543f92ebe9f0eb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
typealias CompletionHandler = (Data) -> Void | |
typealias FailureHandler = (APIError) -> Void | |
struct EmptyRequest: Encodable {} // Added this | |
struct EmptyResponse: Decodable {} // Added this | |
enum HTTPMethod: String { | |
case get | |
case put | |
case delete | |
case post | |
} | |
class APIRequest<Parameters: Encodable, Model: Decodable> { | |
static func call( | |
scheme: String = Config.shared.scheme, | |
host: String = Config.shared.host, | |
path: String, | |
method: HTTPMethod, | |
authorized: Bool, // Added this | |
queryItems: [URLQueryItem]? = nil, // Added this | |
parameters: Parameters? = nil, | |
completion: @escaping CompletionHandler, | |
failure: @escaping FailureHandler | |
) { | |
if !NetworkMonitor.shared.isReachable { | |
return failure(.noInternet) | |
} | |
var components = URLComponents() | |
components.scheme = scheme | |
components.host = host | |
components.path = path | |
if let queryItems = queryItems { // Added this | |
components.queryItems = queryItems | |
} | |
guard let url = components.url else { | |
return | |
} | |
var request = URLRequest(url: url) | |
request.httpMethod = method.rawValue | |
request.addValue("application/json", forHTTPHeaderField: "Content-Type") | |
request.addValue("application/json", forHTTPHeaderField: "Accept") | |
request.addValue("true", forHTTPHeaderField: "x-mock-match-request-body") | |
if let parameters = parameters { | |
request.httpBody = try? JSONEncoder().encode(parameters) | |
} | |
if authorized, let token = Auth.shared.getAccessToken() { // Added this | |
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization") | |
} | |
let task = URLSession.shared.dataTask(with: request) { data, _, error in | |
if let data = data { | |
completion(data) | |
} else { | |
if error != nil { | |
failure(APIError.response) | |
} | |
} | |
} | |
task.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment