Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlesmuchene/2fa95caf9eda6904717dd8bc94254d9c to your computer and use it in GitHub Desktop.
Save charlesmuchene/2fa95caf9eda6904717dd8bc94254d9c to your computer and use it in GitHub Desktop.
Custom handler using custom serializer
extension DataRequest {
/// Decodes the response to a type `T` or` APIError`.
///
/// NB: The serializer used `TwoDeodableResponseSerializer` doesn't throw though Alamofire
/// response serializer expects to receive a `DataResponse`. All errors/failures are converted to an `APIError`.
///
/// - Parameters:
/// - t: Type to decode to
/// - queue: `DispatchQueue` to dispatch `completionHandler`
/// - errorCode: code to signal error when to fetch `APIError`
/// - completionHandler: Handler called on completion
@discardableResult func responseDecodable<T: Decodable>(queue: DispatchQueue = DispatchQueue.global(qos: .userInitiated), of t: T.Type, errorCode: StatusCode, completionHandler: @escaping (Result<T, APIError>) -> Void) -> Self {
return response(queue: .main, responseSerializer: TwoDecodableResponseSerializer<T>(errorCode: errorCode)) { response in
switch response.result {
case .success(let result):
completionHandler(result)
case .failure(let error):
completionHandler(.failure(.init(error: error)))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment