Last active
March 6, 2019 06:23
-
-
Save H-Ghadirian/9954a8b7e6b02fc33c703401cf217e7e 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
enum HTTPMethod: String { | |
case get = "GET" | |
} | |
class HTTPLayer { | |
let baseURL = URL(string: "https://hamed-gh.com")! | |
func request(at endpoint: Endpoint, completion: @escaping (Data?, Error?) -> Void) { | |
let url = baseURL.appendingPathComponent(endpoint.path) | |
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in | |
completion(data, error) | |
} | |
task.resume() | |
} | |
} | |
enum Endpoint { | |
case listTransactions | |
case transactionDetails(String) | |
var method: HTTPMethod { | |
return .get | |
} | |
var path: String { | |
switch self { | |
case .listTransactions: | |
return "/api/transactions/" | |
case .transactionDetails(let id): | |
return "/api/transactions/id" | |
} | |
} | |
} | |
struct Transaction: Decodable { | |
let id: String | |
let amount: Double | |
} | |
struct TransactionDetails: Decodable { | |
let payload: [String: String] | |
} | |
enum Result<T> { | |
case success(T) | |
case failure(NSError) | |
} | |
class APIClient { | |
let httpLayer: HTTPLayer | |
init(httpLayer: HTTPLayer) { | |
self.httpLayer = httpLayer | |
} | |
func transactions(completion: @escaping (Result<[Transaction]>) -> Void) { | |
self.httpLayer.request(at: .listTransactions) { (data, error) in | |
if error != nil { | |
completion(.failure(error! as NSError)) | |
} else { | |
do { | |
let transactions = try JSONDecoder().decode([Transaction].self, from: data!) | |
completion(.success(transactions)) | |
} catch { | |
completion(.failure(self.defaultError)) | |
} | |
} | |
} | |
} | |
func transactionDetails(for transaction: Transaction, completion: @escaping (Result<TransactionDetails>) -> Void) { | |
self.httpLayer.request(at: .transactionDetails(transaction.id)) { (data, error) in | |
if error != nil { | |
completion(.failure(error! as NSError)) | |
} else { | |
do { | |
let transactions = try JSONDecoder().decode(TransactionDetails.self, from: data!) | |
completion(.success(transactions)) | |
} catch { | |
completion(.failure(self.defaultError)) | |
} | |
} | |
} | |
} | |
var defaultError: NSError = NSError(domain: "", code: 1, userInfo: nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment