How to modify redirect body with Moya? (iOS, Swift, Moya, Alamofire)

431 Views Asked by At

I have an API, https://00.00.00.00/api/commitPayment that in the body has amount value. When request sends, server redirect this request to https://00.00.00.00/api/commitPaymentV3. But redirect has empty body. I need to modify redirect and pass amount from request to redirected request. Address in redirect may change, so I can't just sent requests directly to it.

Request

struct TopUpWithAmountRequest: Codable {
    let amount: Int
    let redirect: Bool
    
    enum CodingKeys: String, CodingKey {
        case amount = "Amount"
        case redirect = "ShouldRedirect"
    }
}

API

import Moya

enum TopUpAPI {
    case topUpWithAmount(request: TopUpWithAmountRequest)
}

extension TopUpAPI: TargetType {
    var baseURL: URL {
        return URL(string: "https://00.00.00.00")!
    }
    
    var path: String {
        switch self {
        case .topUpWithAmount:
            return "/api/commitPayment"
    }
    
    var method: Moya.Method {
        switch self {
        case .topUpWithAmount:
            return .post
    }
    
    var task: Task {
        switch self {
        case .topUpWithAmount(let request):
            return .requestJSONEncodable(request)
    }
    
    var headers: [String : String]? {
        let headers = ServerConstants.httpHeaders
        return headers
    }
}

Service

class TopUpService: TopUpServiceProtocol {
        
    let provider = MoyaProvider<TopUpAPI>()

    func topUp(request: TopUpWithAmountRequest, completion: @escaping (Result<Response, MoyaError>) -> Void) {
        provider.request(.topUpWithAmount(request: request), completion: completion)
    }
}

Caller code

        let request = TopUpWithAmountRequest(amount: Int(amount), redirect: true)
        
        view?.showProgressHUD()
        
        topUpService.topUpWithRedirector(request: request) { [weak self] result in
            switch result {
            case .success(let response):
               ...
            case .failure(let error):
                print("--- Error in TopUpAmount: \(error)")
                self?.view?.showErrorNotification()
               ...
            }
            self?.view?.hideProgressHUD()
        }

I can't realise, how to modify redirect body with Moya. But I did it with Alamofire:

Alamofire solution:

    func topUpWithRedirector(amount: Int, completion: @escaping (DataResponse<TopUpPaymentAFResponse, AFError>) -> Void) {

        let newApi = "https://00.00.00.00/api/commitPayment"
        let request = AF.request(
            newApi,
            method: HTTPMethod.post,
            parameters: ["Amount" : amount, "ShouldRedirect" : true],
            encoding: JSONEncoding.default,
            headers: [ "Content-Type" : "application/json", "MobileReq" : "ios" ]
        )

        let redirector = Redirector(behavior: .modify({ task, request, responce in
            var newRequest: URLRequest = request
            
            let parameters: [String: Any] = [
                "Amount" : amount
            ]

            let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
            newRequest.httpBody = httpBody
            
            return newRequest
        }))
        
        request.redirect(using: redirector).responseDecodable(of: TopUpPaymentAFResponse.self, completionHandler: completion)

    }

So, I need help to realise this with Moya library. Thanks.

0

There are 0 best solutions below