Created
September 11, 2019 19:12
-
-
Save Frankacy/16962c5c788b43d4ece481d87b4e55ec to your computer and use it in GitHub Desktop.
An alternative way to specify RequestTemplate
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
// So this is the same... | |
public enum HTTPMethod: String { | |
case get = "GET" | |
case post = "POST" | |
case put = "PUT" | |
case delete = "DELETE" | |
case patch = "PATCH" | |
} | |
public protocol RequestTemplate { | |
var method: HTTPMethod { get } | |
var path: String { get } | |
var parameters: [URLQueryItem] { get } | |
var headers: [String: String] { get } | |
var body: Data? { get } | |
} | |
// But now we specify this... | |
public extension RequestTemplate { | |
var method: HTTPMethod { return .get } | |
var parameters: [URLQueryItem] { return [] } | |
var body: Data? { return nil } | |
var headers: [String : String] { return [:] } | |
} | |
// Which allows us to define requests with less boilerplate 👇 | |
struct GetCardsRequest: RequestTemplate { | |
let path: String = "cards/" | |
} | |
// And if you want to run it, use this 👇 | |
public class ScryfallServer { | |
let baseURL: URL(string: "https://api.scryfall.com")! | |
public func taskForRequest(_ request: RequestTemplate, | |
completion: @escaping (Result<Data, Error>) -> Void) -> URLSessionTask? { | |
guard let urlRequest = URLRequest(with: request, baseURL: baseURL) else { | |
return nil | |
} | |
let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in | |
if let error = error { | |
completion(.failure(error)) | |
} else if let data = data { | |
completion(.success(data)) | |
} | |
} | |
return dataTask | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment