KamilH
10/14/2020, 8:21 AMHttpClient
? I would like to hide it behind interface for testing and maintainability purposes, but I can’t because its methods are defined as a inline reified
KamilH
10/14/2020, 8:21 AMinterface HttpClient {
suspend fun <T> execute(endpoint: Endpoint): Resource<T>
}
class KtorHttpClient(private val ktor: Ktor) : HttpClient {
override suspend fun <T> execute(endpoint: Endpoint): Resource<T> =
wrapIntoResource {
ktor.request(endpoint.toHttpRequest())
}
private suspend fun <T> wrapIntoResource(executor: suspend () -> T): Resource<T> =
try {
Resource.Data(executor())
} catch (exception: Exception) {
Resource.Error(RepositoryError.handle(exception))
}
}
gildor
10/14/2020, 12:12 PMgildor
10/14/2020, 12:14 PMgildor
10/14/2020, 12:15 PMgildor
10/14/2020, 12:18 PMgildor
10/14/2020, 12:19 PMgildor
10/14/2020, 12:20 PMKamilH
10/14/2020, 12:54 PMApi
classes that contains functions returning Endpoint
instances
2. Endpoint
class describes an endpoint, it has: baseUrl
, method
, path
, body
etc. (return type as KType?)
3. My HttpClient
accepts `Endpoint`s and returns Resource<T>
4. Resource<T>
is either Data
or Error
Using this structure everything is easily swappable and testable, which is very important for me, because I’m working on a multiplatform project where mocking is hard
Of course I can test HttpClient
with MockEngine
and I’m doing it right now (testing if for example on OK
response there is Resource.Data
returned), but in for example Repository
class where I’m using HttpClient
I would like to easily swap its instance with mocked onegildor
10/14/2020, 1:54 PMbut in for exampleBut you still can do this by inject HttpClient instance to repositoryclass where I’m usingRepository
I would like to easily swap its instance with mocked oneHttpClient
gildor
10/14/2020, 1:55 PMI think you can achieve it with custom adapter for deserialization without wrapping whole APIis eitherResource<T>
orData
Error
jorge.rego
10/14/2020, 2:56 PMgildor
10/15/2020, 8:41 AMrequest
function, just go to declaration, you will see how it implemented