|
| 1 | +package com.pratclot.themoviedb |
| 2 | + |
| 3 | +import com.pratclot.DispatcherWrapper |
| 4 | +import com.pratclot.api.MoviesApi |
| 5 | +import com.pratclot.dto.MovieDto |
| 6 | +import com.pratclot.dto.MoviesDto |
| 7 | +import dagger.Binds |
| 8 | +import dagger.Module |
| 9 | +import dagger.hilt.InstallIn |
| 10 | +import dagger.hilt.components.SingletonComponent |
| 11 | +import kotlinx.coroutines.Dispatchers |
| 12 | +import kotlinx.coroutines.suspendCancellableCoroutine |
| 13 | +import kotlinx.coroutines.withContext |
| 14 | +import kotlinx.serialization.decodeFromString |
| 15 | +import kotlinx.serialization.json.Json |
| 16 | +import java.io.FileNotFoundException |
| 17 | +import java.nio.charset.Charset |
| 18 | +import javax.inject.Inject |
| 19 | +import kotlin.coroutines.resumeWithException |
| 20 | + |
| 21 | +private const val FILENAME = "raw/themoviesdb.json" |
| 22 | +private const val FILENAME_ONE_MOVIE = "raw/onemovie.json" |
| 23 | + |
| 24 | +@InstallIn(SingletonComponent::class) |
| 25 | +@Module |
| 26 | +abstract class MoviesApiModule { |
| 27 | + |
| 28 | + class MoviesApiMock @Inject constructor( |
| 29 | + private val json: Json, |
| 30 | + private val dispatcherWrapper: DispatcherWrapper, |
| 31 | + ) : MoviesApi { |
| 32 | + |
| 33 | + private suspend inline fun <reified T> readFromFile(path: String): T = |
| 34 | + withContext(dispatcherWrapper.io) { |
| 35 | + suspendCancellableCoroutine { continuation -> |
| 36 | + val stream = javaClass.classLoader.getResourceAsStream(path) |
| 37 | + if (stream == null) |
| 38 | + continuation.resumeWithException(FileNotFoundException("Did not find ${path}")) |
| 39 | + else stream.run { |
| 40 | + continuation.invokeOnCancellation { close() } |
| 41 | + val size = available() |
| 42 | + val buffer = ByteArray(size) |
| 43 | + read(buffer) |
| 44 | + close() |
| 45 | + val jsonString = buffer.toString(Charset.defaultCharset()) |
| 46 | + json.decodeFromString<T>(jsonString).let { list -> |
| 47 | + continuation.resume(list) { continuation.resumeWithException(it) } |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + override suspend fun getMovies(): MoviesDto = readFromFile(FILENAME) |
| 54 | + |
| 55 | + override suspend fun getMovieById(id: Int): MovieDto = readFromFile(FILENAME_ONE_MOVIE) |
| 56 | + |
| 57 | + } |
| 58 | + |
| 59 | + @Binds |
| 60 | + abstract fun bindMoviesApi(moviesApiMock: MoviesApiMock): MoviesApi |
| 61 | +} |
0 commit comments