Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@MrEldin 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

This comment has been minimized.

Copy link
Owner Author

@charlesmuchene charlesmuchene commented May 6, 2020

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
You can’t perform that action at this time.