Skip to content

Instantly share code, notes, and snippets.

@gabrielepalma
Last active January 10, 2019 08:41
Show Gist options
  • Save gabrielepalma/b9a24d9f0422f2bf50b466797e96d235 to your computer and use it in GitHub Desktop.
Save gabrielepalma/b9a24d9f0422f2bf50b466797e96d235 to your computer and use it in GitHub Desktop.
NetworkManager
class NetworkManager : NetworkManagerProtocol {
var networkConfiguration : NetworkConfigurationProtocol
init(networkConfiguration : NetworkConfigurationProtocol) {
self.networkConfiguration = networkConfiguration
}
func makeRequest(request: Request) -> Promise<Void> {
return firstly {
makeRequestInternal(request: request)
}.map({ r in })
}
func makeRequest<T>(request: Request, responseType: T.Type) -> Promise<T> where T : Decodable, T : Encodable {
return firstly {
makeRequestInternal(request: request)
}.map({ (response) -> T in
return try JSONDecoder().decode(T.self, from: response.body)
})
}
func makeRequest<T>(request: Request, responseType: [T.Type]) -> Promise<[T]> where T : Decodable, T : Encodable {
return firstly {
makeRequestInternal(request: request)
}.map({ (response) -> [T] in
return try JSONDecoder().decode([T].self, from: response.body)
})
}
func makeRequest(request: Request, responseType: Data.Type) -> Promise<Data> {
return firstly {
makeRequestInternal(request: request)
}.map({ (response) -> Data in
return response.body
})
}
private func makeRequestInternal(request : Request) -> Promise<NetworkResponse<Data>> {
let auth = request.authManager ?? PublicAuthorizationHelper()
guard let base = URL(string: networkConfiguration.baseUrl) else {
return Promise<NetworkResponse<Data>>(error: NSError(domain: "NetworkManager", code: 599, userInfo: ["reason" : "URL was invalid "] ))
}
let url = base.appendingPathComponent(request.path)
var urlRequest = URLRequest(url: url)
switch request.contentType {
case .JSON:
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
case .MULTIPART(let boundary):
urlRequest.setValue("multipart/mixed;boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = request.body
urlRequest.httpMethod = request.method.rawValue
for header in request.additionalHeaders {
urlRequest.setValue(header.value, forHTTPHeaderField: header.key)
}
for header in auth.authorizationHeaders() {
urlRequest.setValue(header.value, forHTTPHeaderField: header.key)
}
return DispatchQueue.global().async(.promise) { () -> Promise<Void> in
auth.refreshAccessTokenIfNeeded()
}
.then { (_) -> Promise<(data: Data, response: URLResponse)> in
URLSession.shared.dataTask(.promise, with: urlRequest).validate()
}
.map { (response : (data: Data, response: URLResponse)) -> NetworkResponse<Data> in
NetworkResponse(meta: response.response, body: response.data)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment