Advertisement
McFamous

Untitled

Jul 24th, 2023
1,113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 2.21 KB | None | 0 0
  1. import Foundation
  2. import Alamofire
  3.  
  4. private let API_BASE_URL = "https://auth-test.ecp-share.com/v1"
  5.  
  6. extension Session {
  7.     func requestPayload<T: Decodable>(path: String,
  8.                         method: HTTPMethod = .get,
  9.                         parameters: Parameters? = nil,
  10.                         headers: HTTPHeaders? = nil) async -> Result<Array<T>, NetworkError> {
  11.        
  12.         do {
  13.             let response = try await withCheckedThrowingContinuation { continuation in
  14.                 AF.request(
  15.                     API_BASE_URL + path,
  16.                     method: method,
  17.                     parameters: parameters,
  18.                     headers: headers
  19.                 )
  20.                 .responseData { response in
  21.                     switch(response.result) {
  22.                     case let .success(data):
  23.                         continuation.resume(returning: data)
  24.                     case let .failure(error):
  25.                         continuation.resume(throwing: error)
  26.                     }
  27.                 }
  28.             }
  29.            
  30.             do {
  31.                 let apiResponse: APIResponse<T> = try JSONDecoder().decode(APIResponse<T>.self, from: response)
  32.                 guard let result = apiResponse.result else { return .failure(NetworkError())}
  33.                
  34.                 return .success(result.items)
  35.             }
  36.             catch {
  37.                 let apiResponse: APIResponse<APIError> = try JSONDecoder().decode(APIResponse<APIError>.self, from: response)
  38.                 guard let errors = apiResponse.errors else { return .failure(NetworkError(description: "1"))}
  39.            
  40.                 let error = errors.items[0]
  41.                 return .failure(
  42.                     NetworkError(
  43. //                        errorType: error.errorType,
  44.                         paramName: error.paramName,
  45. //                        obtainedValue: error.obtainedValue,
  46.                         description: error.description ?? "2"
  47. //                        details: error.details
  48.                     )
  49.                 )
  50.             }
  51.         }
  52.         catch {
  53.             debugPrint(error)
  54.             return .failure(NetworkError(description: "3"))
  55.         }
  56.     }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement