Is there a way to use Alamofire's ResponseSerializers through Moya?

Viewed 106

I've looked through the documentation and source code of Moya and haven't found any way to make use of Alamofire's ResponseSerializers while running requests through Moya.

Is there any way to do this?

What I'm trying to do

Use Alamofire's AuthenticationInterceptor with a REST API that sends 401 errors inside the JSON body of the response instead of the HTTP Header.

Why this doesn't work

When using Alamofire's AuthenticationInterceptor, the retry behaviour is only triggered when an error occurs inside Alamofire's Request Pipeline.

Because the 401 error is in the JSON body of a 200 OK response, it is never caught by Alamofire.

Any wrapper that we make around MoyaProvider will be able to handle serialization, but at this point we are already outside of Alamofire's Request Pipeline, and therefore, any error that we throw will not trigger the AuthenticationInterceptor's retry behaviour.

What I've had to do

Change Moya's source code directly to inject a responseSerializer in Moya+Alamofire.swift, as seen below:

extension DataRequest: Requestable {
    internal func response(callbackQueue: DispatchQueue?, completionHandler: @escaping RequestableCompletion) -> Self {
        if let callbackQueue = callbackQueue {
            return response(queue: callbackQueue, [ADDED THIS] ---> responseSerializer: CustomDataSerializer() <--- ) { handler in
                completionHandler(handler.response, handler.request, handler.data, handler.error)
            }
        } else {
            return response( [ADDED THIS] ---> responseSerializer: CustomDataSerializer() <--- ) { handler in
                completionHandler(handler.response, handler.request, handler.data, handler.error)
            }
        }
    }
}

TLDR

Can Alamofire's ResponseSerializers be used through Moya?

0 Answers
Related