Skip to content

Instantly share code, notes, and snippets.

@charlesmuchene
Created February 12, 2020 19:02
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/afb68afb136f4dcba39b5432cd6ab10c to your computer and use it in GitHub Desktop.
Save charlesmuchene/afb68afb136f4dcba39b5432cd6ab10c to your computer and use it in GitHub Desktop.
Alamofire custom serializer
//
// TwoDecodableResponseSerializer.swift
//
// Created by Charles Muchene on 2/12/20.
// Copyright © 2020 SenseiDevs. All rights reserved.
//
import Alamofire
import Foundation
final class TwoDecodableResponseSerializer<T: Decodable>: ResponseSerializer {
lazy var decoder: JSONDecoder = {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
return decoder
}()
private let errorCode: StatusCode
init(errorCode: StatusCode) {
self.errorCode = errorCode
}
private lazy var successSerializer = DecodableResponseSerializer<T>(decoder: decoder)
private lazy var errorSerializer = DecodableResponseSerializer<APIError>(decoder: decoder)
public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Result<T, APIError> {
guard error == nil else { return .failure(.init(error: error)) }
guard let response = response else { return .failure(.noResponseError) }
do {
if response.statusCode == errorCode {
let result = try errorSerializer.serialize(request: request, response: response, data: data, error: nil)
return .failure(result)
} else {
let result = try successSerializer.serialize(request: request, response: response, data: data, error: nil)
return .success(result)
}
} catch(let err) {
return .failure(.init(error: err))
}
}
}
@MrEldin
Copy link

MrEldin commented May 3, 2020

This class does not conform to DataResponseSerializerProtocol protocol anymore, I don't know if that is a problem with a new Alamofire 5.* but this is not working anymore.

@charlesmuchene
Copy link
Author

Seems it should work. APIError should conform to protocol Error to be used in Swift's Result type. Could you provide a sample code showing the error you get?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment