|
1 | 1 | package data.repository |
2 | 2 |
|
3 | | -import WeatherRepository |
4 | 3 | import domain.models.CurrentWeather |
5 | | -import domain.models.exceptions.FailedFetchWeatherDataException |
| 4 | +import domain.models.FailedFetchWeatherDataException |
| 5 | +import domain.models.NoLocationRetrieved |
| 6 | +import domain.repository.WeatherRepository |
6 | 7 | import io.ktor.client.* |
7 | | -import io.ktor.client.call.* |
8 | 8 | import io.ktor.client.request.* |
9 | 9 | import io.ktor.client.statement.* |
10 | 10 | import io.ktor.http.* |
| 11 | +import kotlinx.serialization.json.Json |
| 12 | +import org.json.JSONObject |
11 | 13 |
|
12 | 14 | const val OPEN_METO_API = "https://api.open-meteo.com/v1/forecast" |
13 | 15 |
|
14 | 16 | class WeatherRepositoryImpl(private val httpClient: HttpClient) : WeatherRepository { |
15 | 17 | override suspend fun getCurrentWeather(latitude: Double, longitude: Double): CurrentWeather { |
16 | | - val response: HttpResponse = httpClient.get(OPEN_METO_API) { |
| 18 | + val httpResponse: HttpResponse = httpClient.get(OPEN_METO_API) { |
17 | 19 | parameter("latitude", latitude) |
18 | 20 | parameter("longitude", longitude) |
19 | 21 | parameter( |
20 | 22 | "current", |
21 | | - "temperature_2m,relative_humidity_2m,apparent_temperature,is_day,wind_speed_10m,snowfall,rain,weather_code,cloud_cover" |
| 23 | + "temperature_2m,relative_humidity_2m,apparent_temperature,is_day,rain,showers,snowfall,wind_speed_10m,cloud_cover" |
22 | 24 | ) |
23 | 25 | } |
24 | 26 |
|
25 | | - if (!response.status.isSuccess()) { |
| 27 | + if (httpResponse.status != HttpStatusCode.OK) { |
26 | 28 | throw FailedFetchWeatherDataException( |
27 | | - "Weather API returned error status: ${response.status}" |
| 29 | + "Weather API returned error status: ${httpResponse.status}" |
28 | 30 | ) |
29 | 31 | } |
30 | 32 |
|
31 | | - return response.body() |
| 33 | + try { |
| 34 | + val response = JSONObject(httpResponse.bodyAsText()).get("current").toString() |
| 35 | + val json = Json { |
| 36 | + ignoreUnknownKeys = true |
| 37 | + } |
| 38 | + return json.decodeFromString<CurrentWeather>(response) |
| 39 | + } catch (e: Exception) { |
| 40 | + throw NoLocationRetrieved() |
| 41 | + } |
32 | 42 | } |
33 | 43 | } |
0 commit comments