Fallback geocode when postal code has zero results
All checks were successful
build-and-deploy / build-deploy (push) Successful in 32s

This commit is contained in:
androidlover5842
2026-01-31 11:12:51 +05:30
parent 0771631b5a
commit 6202a0e814

View File

@@ -28,16 +28,39 @@ class GoogleGeocodingClient(
.queryParam("region", "IN")
.queryParam("key", apiKey)
.toUriString()
val response = restTemplate.getForEntity(url, String::class.java)
val body = response.body ?: return GeocodeResult(null, null, "EMPTY_BODY")
val parsed = parseCityState(body)
GeocodeResult(parsed, body, "OK")
val primary = fetch(url)
if (primary.status == "OK") {
return primary
}
if (primary.status == "ZERO_RESULTS") {
val fallbackUrl = UriComponentsBuilder.fromUriString(baseUrl)
.queryParam("address", "$pinCode India")
.queryParam("region", "IN")
.queryParam("key", apiKey)
.toUriString()
val fallback = fetch(fallbackUrl)
if (fallback.resolvedCityState != null) return fallback
return primary
}
primary
} catch (ex: Exception) {
logger.warn("Geocoding failed: {}", ex.message)
GeocodeResult(null, null, "ERROR")
}
}
private fun fetch(url: String): GeocodeResult {
val response = restTemplate.getForEntity(url, String::class.java)
val body = response.body ?: return GeocodeResult(null, null, "EMPTY_BODY")
val status = parseStatus(body)
val parsed = if (status == "OK") parseCityState(body) else null
return GeocodeResult(parsed, body, status ?: "UNKNOWN_STATUS")
}
private fun parseStatus(body: String): String? {
return objectMapper.readTree(body).path("status").asText(null)
}
private fun parseCityState(body: String): String? {
val root = objectMapper.readTree(body)
val results = root.path("results")