Replies: 2 comments 2 replies
-
@inwoodev You'll need to convert the data to the decodable type somehow. Assuming it's JSON, you can use a JSONDecoder: return try JSONDecoder().decode(T.self, from: data) |
Beta Was this translation helpful? Give feedback.
1 reply
-
Thank you. I think I was very sleepy at the very moment when I asked the question. With your enlightenment and with clear mind, I was able to figure it out:) Thank you again~ import ComposableArchitecture
import Foundation
enum APIError: Error {
case encodingDecodingError
}
struct APIClient {
var _request: (APIEndpoint) async throws -> Data
func request<T: Decodable>(endpoint: APIEndpoint, as type: T.Type) async throws -> T {
return try await JSONDecoder().decode(T.self, from: self._request(endpoint))
}
}
extension APIClient: DependencyKey {
static var liveValue: APIClient {
return Self(
_request: { endpoint in
guard let url = URL(string: endpoint.urlString) else {
throw APIError.encodingDecodingError
}
var request = URLRequest(url: url)
request.httpMethod = endpoint.method.rawValue
let (data, _) = try await URLSession.shared.data(for: request)
return data
})
}
}
// MARK: - Dependency
extension DependencyValues {
var apiClient: APIClient {
get { self[APIClient.self] }
set { self[APIClient.self] = newValue}
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello, I am trying to build a testable generic api client that returns decodable type.
here is the api endpoint type that I am thinking of using:
I have checked other Q&A's and figured out that generic types could be used with helper methods, so I tried to set up in a similar way, but I am stuck here:
any reference, or idea would be appreciated.🥲
Beta Was this translation helpful? Give feedback.
All reactions