Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @discardableResult
- private func performRequest<T:Decodable>(route: APIRouter, decoder: JSONDecoder = JSONDecoder(), completion:@escaping (Int, Result<T>)->Void) -> DataRequest {
- return Alamofire.request(route).responseData() { responseData in
- guard let response = responseData.response else {
- completion(APIClient.responseErrorCode, .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
- return
- }
- print(response)
- switch response.statusCode {
- case 200...299 : //This case will parse the T type.
- guard let data = responseData.data else {
- completion(APIClient.parsingJsonErrorCode,
- .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
- return
- }
- do {
- let responseCodableObject = try decoder.decode(T.self, from: data)
- print("responseCodableObject: \(responseCodableObject)")
- completion(response.statusCode, .success(responseCodableObject))
- } catch let error {
- print("Parsing Error: \(error)")
- completion(APIClient.parsingJsonErrorCode,
- .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
- }
- case 400: //This case will parse the ErrorMessageResponse type
- guard let data = responseData.data else {
- completion(APIClient.parsingJsonErrorCode, .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
- return
- }
- do {
- let errorMessage = try decoder.decode(ErrorMessageResponse.self, from: data)
- print("errorMessage: \(errorMessage)")
- completion(response.statusCode, .failure(ApiError.internalServerError(errorMessage.mensaje)))
- } catch let error {
- print("Parsing Error: \(error)")
- completion(APIClient.parsingJsonErrorCode,
- .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
- }
- case 403:
- completion(response.statusCode, .failure(ApiError.invalidToken))
- default:
- completion(APIClient.responseErrorCode,
- .failure(ApiError.internalServerError(NSLocalizedString("service_error", comment: AppConstant.EMPTY))))
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement