Skip to content

Instantly share code, notes, and snippets.

@szotp
Last active January 6, 2021 02:26
Show Gist options
  • Save szotp/0498e7adb7e093b8600425c4baabb888 to your computer and use it in GitHub Desktop.
Save szotp/0498e7adb7e093b8600425c4baabb888 to your computer and use it in GitHub Desktop.
Extremely generic swagger client
import Foundation
typealias ApiCallback<Output> = Optional<(Result<Output, Error>) -> Void>
protocol EndpointClient {
func execute<Output>(endpoint: Endpoint<Output>, onResult: ApiCallback<Output>)
}
struct RequestBuilder {
var path: String = ""
var headers: [String: String] = [:]
var query: [String: Encodable] = [:]
var body: Encodable?
var tags: Set<String> = []
}
struct Endpoint<Output: Decodable> {
let client: EndpointClient
let request: RequestBuilder
func execute(onResult: ApiCallback<Output>) {
client.execute(endpoint: self, onResult: onResult)
}
}
// MARK: - Code generated by Swagger
struct LoginResponse: Codable {
var token: String
}
struct GeneratedApi {
let client: EndpointClient
/// Generated documentation
func login(name: String, password: String) -> Endpoint<LoginResponse> {
var req = RequestBuilder()
req.path = "/login"
req.query["name"] = name
req.query["password"] = password
return Endpoint(client: client, request: req)
}
}
// MARK: - Code that I will write myself according to my preferences.
extension URLSession: EndpointClient {
func execute<T>(endpoint: Endpoint<T>, onResult: ApiCallback<T>) {
/// TODO: run dataTask or something
}
var generated: GeneratedApi {
return GeneratedApi(client: self)
}
}
func loginExample() {
let client = URLSession.shared
client.generated.login(name: "login", password: "password").execute { result in
print(result)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment