Skip to content

Commit

Permalink
feat: Provide places data source
Browse files Browse the repository at this point in the history
  • Loading branch information
ngallazzi committed Sep 2, 2024
1 parent a923d48 commit f5b4405
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.ngallazzi.places.data

import com.ngallazzi.places.data.dto.AutocompleteDTO
import com.ngallazzi.places.domain.PlacesDataSource
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.http.ContentType
import io.ktor.http.HttpStatusCode
import io.ktor.http.contentType

internal class PlacesRemoteDataSource(
private val httpClient: HttpClient
) :
PlacesDataSource {
override suspend fun searchCity(name: String, languageCode: String): Result<AutocompleteDTO> {
return handleNetworkCall("maps/api/place/autocomplete/json?input=$name&types=(cities)&language=$languageCode")
}

override suspend fun searchCountry(
name: String,
languageCode: String
): Result<AutocompleteDTO> {
return handleNetworkCall("maps/api/place/autocomplete/json?input=$name&type=country&language=$languageCode")
}

override suspend fun searchAddress(
address: String,
languageCode: String
): Result<AutocompleteDTO> {
return handleNetworkCall("maps/api/place/autocomplete/json?input=$address&type=geocode&language=$languageCode")
}

private suspend fun handleNetworkCall(url: String): Result<AutocompleteDTO> {
return try {
val result = httpClient.get(url) {
contentType(ContentType.Application.Json)
}
return when (result.status) {
HttpStatusCode.OK -> {
val response = result.body<AutocompleteDTO>()
when (response.status) {
"OK" -> Result.success(response)
"REQUEST_DENIED" -> Result.failure(Exception("Invalid api key"))
else -> Result.failure(Exception(response.status))
}
}

else -> Result.failure(Exception(Exception(result.toString())))
}

} catch (e: Exception) {
Result.failure(Throwable(e))
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.ngallazzi.places.domain

import com.ngallazzi.places.data.dto.AutocompleteDTO

internal interface PlacesDataSource {
suspend fun searchCity(name: String, languageCode: String): Result<AutocompleteDTO>

suspend fun searchCountry(name: String, languageCode: String): Result<AutocompleteDTO>

suspend fun searchAddress(
address: String,
languageCode: String
): Result<AutocompleteDTO>
}

0 comments on commit f5b4405

Please sign in to comment.