Created
November 21, 2016 11:02
-
-
Save thiagolioy/165aa28608d4f3c9916fda0bec8bcbc3 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 | |
import Moya | |
import RxSwift | |
import ObjectMapper | |
import Moya_ObjectMapper | |
extension Response { | |
func removeAPIWrappers() -> Response { | |
guard let json = try? self.mapJSON() as? Dictionary<String, AnyObject>, | |
let results = json?["data"]?["results"] ?? [], | |
let newData = try? JSONSerialization.data(withJSONObject: results, options: .prettyPrinted) else { | |
return self | |
} | |
let newResponse = Response(statusCode: self.statusCode, | |
data: newData, | |
response: self.response) | |
return newResponse | |
} | |
} | |
struct MarvelAPIManager { | |
let provider: RxMoyaProvider<MarvelAPI> | |
let disposeBag = DisposeBag() | |
init() { | |
provider = RxMoyaProvider<MarvelAPI>() | |
} | |
} | |
extension MarvelAPIManager { | |
typealias AdditionalStepsAction = (() -> ()) | |
fileprivate func requestObject<T: Mappable>(_ token: MarvelAPI, type: T.Type, | |
completion: @escaping (T?) -> Void, | |
additionalSteps: AdditionalStepsAction? = nil) { | |
provider.request(token) | |
.debug() | |
.mapObject(T.self) | |
.subscribe { event -> Void in | |
switch event { | |
case .next(let parsedObject): | |
completion(parsedObject) | |
additionalSteps?() | |
case .error(let error): | |
print(error) | |
completion(nil) | |
default: | |
break | |
} | |
}.addDisposableTo(disposeBag) | |
} | |
fileprivate func requestArray<T: Mappable>(_ token: MarvelAPI, type: T.Type, | |
completion: @escaping ([T]?) -> Void, | |
additionalSteps: AdditionalStepsAction? = nil) { | |
provider.request(token) | |
.debug() | |
.map { response -> Response in | |
return response.removeAPIWrappers() | |
} | |
.mapArray(T.self) | |
.subscribe { event -> Void in | |
switch event { | |
case .next(let parsedArray): | |
completion(parsedArray) | |
additionalSteps?() | |
case .error(let error): | |
print(error) | |
completion(nil) | |
default: | |
break | |
} | |
}.addDisposableTo(disposeBag) | |
} | |
} | |
extension MarvelAPIManager { | |
func characters(query: String? = nil, completion: @escaping ([Character]?) -> Void) { | |
requestArray(.characters(query), | |
type: Character.self, | |
completion: completion) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment