Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NetworkLayerCallBackTypeRequestExecutor.swift
class WebApiClient: RequestExecutor {
private var configuration: URLSessionConfiguration
private var session: URLSession
init(sessionConfiguration: URLSessionConfiguration = URLSessionConfiguration.default) {
configuration = URLSession.shared.configuration
session = URLSession(configuration: configuration)
}
func executeRequest<R>(_ request: R, completion: @escaping (Result<R.Response, Error>) -> Void) where R : RequestConvertable {
guard let requestt = try? request.asURLRequest() else {
completion(.failure(APIError.badRequest()))
return
}
session.dataTask(with: requestt) { [self] data, response, error in
guard error == nil else {
if let httpResponse = response as? HTTPURLResponse {
completion(.failure(parseError(data: data, response: httpResponse, errorParser: request.errorParser)))
} else {
completion(.failure(APIError.invalidResponse()))
}
return
}
guard let data = data else {
completion(.failure(APIError.invalidResponse()))
return
}
if let parser = request.parser {
do {
completion(.success(try parser.parse(data: data)))
} catch {
completion(.failure(APIError.parseError(error)))
}
}else {
do {
completion(.success(try JSONDecoder().decode(R.Response.self, from: data)))
} catch {
completion(.failure(APIError.parseError(error)))
}
}
}.resume()
}
private
func parseError(data: Data?, response: URLResponse, errorParser: ErrorParserType?) -> Error {
var errorToReturn: Error?
if let httpUrlResponse = response as? HTTPURLResponse {
if let errorParser = errorParser, let errorData = data
{
if let json = try? JSONSerialization.jsonObject(with: errorData, options: []) as? JSONDictionary {
if let parsedError = errorParser.parse(data: json) {
errorToReturn = parsedError
}
}
}
switch httpUrlResponse.statusCode {
case 400:
errorToReturn = APIError.badRequest(errorToReturn)
case 401:
errorToReturn = APIError.unAuthorised(errorToReturn)
case 404:
errorToReturn = APIError.notFound(errorToReturn)
case 400...499:
break
case 500...599:
errorToReturn = APIError.serverError()
default:
errorToReturn = APIError.unknown()
}
}
return errorToReturn ?? APIError.invalidResponse()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment