Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.88 KB | None | 0 0
  1. @discardableResult
  2. private func performRequest<T:Decodable>(route: APIRouter, decoder: JSONDecoder = JSONDecoder(), completion:@escaping (Int, Result<T>)->Void) -> DataRequest {
  3.  
  4. return Alamofire.request(route).responseData() { responseData in
  5.  
  6. guard let response = responseData.response else {
  7. completion(APIClient.responseErrorCode, .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
  8. return
  9. }
  10.  
  11. print(response)
  12.  
  13. switch response.statusCode {
  14.  
  15. case 200...299 : //This case will parse the T type.
  16.  
  17. guard let data = responseData.data else {
  18. completion(APIClient.parsingJsonErrorCode,
  19. .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
  20. return
  21. }
  22.  
  23. do {
  24. let responseCodableObject = try decoder.decode(T.self, from: data)
  25. print("responseCodableObject: \(responseCodableObject)")
  26. completion(response.statusCode, .success(responseCodableObject))
  27. } catch let error {
  28. print("Parsing Error: \(error)")
  29. completion(APIClient.parsingJsonErrorCode,
  30. .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
  31. }
  32.  
  33. case 400: //This case will parse the ErrorMessageResponse type
  34.  
  35. guard let data = responseData.data else {
  36. completion(APIClient.parsingJsonErrorCode, .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
  37. return
  38. }
  39.  
  40. do {
  41. let errorMessage = try decoder.decode(ErrorMessageResponse.self, from: data)
  42. print("errorMessage: \(errorMessage)")
  43. completion(response.statusCode, .failure(ApiError.internalServerError(errorMessage.mensaje)))
  44. } catch let error {
  45. print("Parsing Error: \(error)")
  46. completion(APIClient.parsingJsonErrorCode,
  47. .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
  48. }
  49. case 403:
  50. completion(response.statusCode, .failure(ApiError.invalidToken))
  51. default:
  52. completion(APIClient.responseErrorCode,
  53. .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
  54. }
  55. }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement