Created
April 25, 2018 01:10
-
-
Save trupin/92b3e7b6c3b1a52a848dd7fcb58bf03c 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
final class MovieManager: MovieManaging { | |
let client: ClientProtocol | |
let store: KeyValueStoring | |
init(client: ClientProtocol, store: KeyValueStoring) { | |
self.client = client | |
self.store = store | |
} | |
/// Fetches popular movies from the server, then stores them. | |
func getPopularMovies(_ completion: @escaping (Result<[Movie], MovieManagerError>) -> Void) { | |
client.get(path: "/movies/popular") { (result: Result<[Movie], MovieManagerError>) in | |
switch result { | |
case .success(let movies): | |
for movie in movies { | |
self.store.set(value: movie, for: movie.id) | |
} | |
completion(.success(movies)) | |
case .failure(let error): | |
// handles error... | |
completion(.failure(error)) | |
} | |
} | |
} | |
/// Fetches a movie from the store if it exists, from the server otherwise. | |
func getMovie(id movieID: String, completion: @escaping (Result<Movie, MovieManagerError>) -> Void) { | |
store.getValue(for: movieID) { (result: Result<Movie?, KeyValueStoreError>) in | |
switch result { | |
case .success(.some(let storedMovie)): | |
completion(.success(storedMovie)) | |
case .success(.none): | |
client.get(path: "/movies/\(movieID)") { (result: Result<[Movie], ClientError>) in | |
switch result { | |
case .success(let movie): | |
self.store.set(value: movie, for: movie.id) | |
completion(movie) | |
case .failure(let error): | |
completion(.failure(.client(error))) | |
} | |
} | |
case .failure(let error): | |
completion(.failure(.store(error))) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment