Created
March 25, 2018 19:39
-
-
Save khanlou/b6b3818f7ca7160a9d88ececdd7a34f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum SharedNetworkClient { | |
static let googleMaps: NetworkClient = { | |
let keyBehavior = AddQueryItemsBehavior(name: "key", value: "$YR_KEY") | |
let configuration = RequestConfiguration(baseURLString: "https://maps.googleapis.com/", defaultRequestBehavior: keyBehavior) | |
let client = NetworkClient(configuration: configuration) | |
return client | |
}() | |
} | |
struct AddQueryItemsBehavior: RequestBehavior { | |
let queryItems: [URLQueryItem] | |
init(queryItems: [URLQueryItem]) { | |
self.queryItems = queryItems | |
} | |
init(name: String, value: String?) { | |
self.init(queryItems: [URLQueryItem(name: name, value: value)]) | |
} | |
func modify(request: URLRequest) -> URLRequest { | |
var copy = request | |
guard let url = copy.url else { fatalError() } | |
guard var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) else { fatalError() } | |
urlComponents.queryItems = (urlComponents.queryItems ?? []) + queryItems | |
guard let newURL = urlComponents.url else { fatalError() } | |
copy.url = newURL | |
return copy | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment