Skip to content

Commit

Permalink
Refactor client to separate methods for creating and sending a request
Browse files Browse the repository at this point in the history
  • Loading branch information
mattt committed Jul 19, 2024
1 parent 8f04fb1 commit 3fd73c6
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion Sources/Replicate/Client.swift
Original file line number Diff line number Diff line change
Expand Up @@ -649,13 +649,19 @@ public class Client {
params = ["cursor": "\(cursor)"]
}

return try await fetch(method, path, params: params)
let request = try createRequest(method: method, path: path, params: params)
return try await sendRequest(request)
}

private func fetch<T: Decodable>(_ method: Method,
_ path: String,
params: [String: Value]? = nil)
async throws -> T {
let request = try createRequest(method: method, path: path, params: params)
return try await sendRequest(request)
}

private func createRequest(method: Method, path: String, params: [String: Value]? = nil) throws -> URLRequest {
var urlComponents = URLComponents(string: self.baseURLString.appending(path))
var httpBody: Data? = nil

Expand All @@ -673,6 +679,10 @@ public class Client {
let encoder = JSONEncoder()
httpBody = try encoder.encode(params)
}
case .query:
if let params, let queryString = params["query"] {
httpBody = queryString.description.data(using: .utf8)
}
}

guard let url = urlComponents?.url else {
Expand All @@ -696,6 +706,10 @@ public class Client {
request.addValue(userAgent, forHTTPHeaderField: "User-Agent")
}

return request
}

private func sendRequest<T: Decodable>(_ request: URLRequest) async throws -> T {
let (data, response) = try await session.data(for: request)

let decoder = JSONDecoder()
Expand Down

0 comments on commit 3fd73c6

Please sign in to comment.