blazor-pw-test/Services/WeatherService.cs
2025-04-07 11:45:14 -05:00

81 lines
2.5 KiB
C#

using System.Net.Http.Json;
using MemphisWeatherApp.Models;
namespace MemphisWeatherApp.Services
{
public class WeatherService
{
private readonly HttpClient _httpClient;
private const string ApiKey = "baf21bc93e198c3367ee2f3dae4fd38c"; // Top Secret!!
public WeatherService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<WeatherInfo> GetWeatherAsync()
{
try
{
var response = await _httpClient.GetFromJsonAsync<OpenWeatherResponse>(
$"https://api.openweathermap.org/data/2.5/weather?q=Memphis,us&units=imperial&appid={ApiKey}");
if (response == null)
return new WeatherInfo {
City = "Memphis",
Description = "Data unavailable",
Temperature = 0,
Icon = ""
};
return new WeatherInfo
{
City = "Memphis",
Temperature = response.Main.Temp,
Description = response.Weather[0].Description,
Humidity = response.Main.Humidity,
WindSpeed = response.Wind.Speed,
Icon = $"https://openweathermap.org/img/wn/{response.Weather[0].Icon}@2x.png"
};
}
catch
{
// Return if API broken
return new WeatherInfo
{
City = "Memphis",
Temperature = 404,
Description = "API Broke",
Humidity = 100,
WindSpeed = 200,
Icon = "https://openweathermap.org/img/wn/02d@2x.png"
};
}
}
}
// Response model for OpenWeatherMap API
public class OpenWeatherResponse
{
public WeatherMain Main { get; set; } = new();
public WeatherWind Wind { get; set; } = new();
public WeatherItem[] Weather { get; set; } = Array.Empty<WeatherItem>();
}
public class WeatherMain
{
public double Temp { get; set; }
public int Humidity { get; set; }
}
public class WeatherWind
{
public double Speed { get; set; }
}
public class WeatherItem
{
public string Description { get; set; } = string.Empty;
public string Icon { get; set; } = string.Empty;
}
}