Last active
January 6, 2021 02:26
-
-
Save szotp/0498e7adb7e093b8600425c4baabb888 to your computer and use it in GitHub Desktop.
Extremely generic swagger client
This file contains 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
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