diff --git a/HomeApi/Controllers/HomeController.cs b/HomeApi/Controllers/HomeController.cs index ff0a316..a561a39 100644 --- a/HomeApi/Controllers/HomeController.cs +++ b/HomeApi/Controllers/HomeController.cs @@ -1,149 +1,18 @@ -using System.Globalization; -using System.Text.Json; +using HomeApi.Handlers; using HomeApi.Models; +using MediatR; using Microsoft.AspNetCore.Mvc; -using Microsoft.Extensions.Options; namespace HomeApi.Controllers; [ApiController] [Route("[controller]")] -public class HomeController : ControllerBase +public class HomeController(IMediator mediator) : ControllerBase { - private readonly ILogger _logger; - private readonly IHttpClientFactory _httpClientFactory; - - // get configuration from appsettings.json - private readonly ApiConfiguration _apiConfiguration; - - public HomeController(ILogger logger, IHttpClientFactory httpClientFactory, IOptions apiConfiguration) - { - _logger = logger; - _apiConfiguration = apiConfiguration.Value; - _httpClientFactory = httpClientFactory; - } - [HttpGet(Name = "GetHome")] - public async Task Get() + public async Task> Get() { - var client = _httpClientFactory.CreateClient(); - var cordinates = await GetCoordinatesAsync(_apiConfiguration.DefaultCity); - var auroraJson = await client.GetStringAsync($"http://api.auroras.live/v1/?type=all&lat={cordinates.Value.Latitude}&long={cordinates.Value.Longitude}&forecast=false&threeday=false"); - var auroraForecast = JsonSerializer.Deserialize(auroraJson); - - var url = - $"{_apiConfiguration.BaseUrls.Weather}/forecast.json?key={_apiConfiguration.Keys.Weather}&q={cordinates.Value.Latitude},{cordinates.Value.Longitude}&days=7&lang=sv&aqi=yes&alerts=yes"; - var response = await client.GetAsync(url); - - response.EnsureSuccessStatusCode(); - - var json = await response.Content.ReadAsStringAsync(); - var weather = JsonSerializer.Deserialize(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); - - var forecasts = weather.Forecast.Forecastday.Select(day => new Models.Forecast - { - Date = day.Date, - MaxTempC = day.Day.Maxtemp_C, - MinTempC = day.Day.Mintemp_C, - DayIcon = day.Day.Condition.Icon, - Astro = new Models.Astro { - Moon_Illumination = day.Astro.Moon_Illumination, - Moon_Phase = day.Astro.Moon_Phase, - Moonrise = day.Astro.Moonrise, - Moonset = day.Astro.Moonset, - Sunrise = day.Astro.Sunrise, - Sunset = day.Astro.Sunset - }, - Day = MapSummary(day.Hour.Where(h => h.Is_Day == 1)), - Night = MapSummary(day.Hour.Where(h => h.Is_Day == 0)) - }).ToList(); - - var result = new Home - { - CityName = cordinates.Value.name, - Current = new Models.Current - { - Date = DateTime.Now.ToString(CultureInfo.CurrentCulture), - Feelslike = weather.Current.Feelslike_C, - IsDay = weather.Current.Is_Day, - WindPerHour = weather.Current.Wind_Kph, - WindGustPerHour = weather.Current.Gust_Kph, - Temperature = weather.Current.Temp_C, - AuroraProbability = new Probability - { - Date = auroraForecast.Date, - Calculated = new Models.CalculatedProbability - { - Value = auroraForecast.Probability.Calculated.Value, - Colour = auroraForecast.Probability.Calculated.Colour, - Lat = auroraForecast.Probability.Calculated.Lat, - Long = auroraForecast.Probability.Calculated.Long - }, - Colour = auroraForecast.Probability.Colour, - Value = auroraForecast.Probability.Value, - HighestProbability = new Highest - { - Colour = auroraForecast.Probability.Highest.Colour, - Lat = auroraForecast.Probability.Highest.Lat, - Long = auroraForecast.Probability.Highest.Long, - Value = auroraForecast.Probability.Highest.Value, - Date = auroraForecast.Probability.Highest.Date - } - }, - }, - Forecast = forecasts, - }; - return result; - } - - private WeatherSummary MapSummary(IEnumerable hours) - { - if (!hours.Any()) - return null; - - return new WeatherSummary - { - ConditionText = hours.GroupBy(h => h.Condition.Text).OrderByDescending(g => g.Count()).First().Key, - ConditionIcon = hours.GroupBy(h => h.Condition.Icon).OrderByDescending(g => g.Count()).First().Key, - AvgTempC = Math.Round(hours.Average(h => h.Temp_C), 1), - AvgFeelslikeC = Math.Round(hours.Average(h => h.Feelslike_C), 1), - TotalChanceOfRain = (int)Math.Round(hours.Average(h => h.Chance_Of_Rain)), - TotalChanceOfSnow = (int)Math.Round(hours.Average(h => h.Chance_Of_Snow)) - }; - } - - public async Task<(double Latitude, double Longitude, string name)?> GetCoordinatesAsync(string address) - { - using var client = new HttpClient(); - - client.DefaultRequestHeaders.Add("User-Agent", "dotnet-geocoder-app"); - - var url = $"https://nominatim.openstreetmap.org/search?q={Uri.EscapeDataString(address)}&format=json&limit=1"; - - var response = await client.GetAsync(url); - - if (!response.IsSuccessStatusCode) - return null; - - var content = await response.Content.ReadAsStringAsync(); - - var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; - var results = JsonSerializer.Deserialize(content, options); - - if (!(results?.Length > 0)) - return null; - - var lat = double.Parse(results[0].Lat); - var lon = double.Parse(results[0].Lon); - var name = results[0].name; - return (lat, lon, name); - - } - - private class NominatimResult - { - public string Lat { get; set; } - public string Lon { get; set; } - public string name { get; set; } + var result = await mediator.Send(new GetWeather.Command()); + return Ok(result); } } \ No newline at end of file diff --git a/HomeApi/Extensions/ContractExtensions.cs b/HomeApi/Extensions/ContractExtensions.cs new file mode 100644 index 0000000..8937159 --- /dev/null +++ b/HomeApi/Extensions/ContractExtensions.cs @@ -0,0 +1,129 @@ +using System.Globalization; +using HomeApi.Models; +using HomeApi.Models.Response; +using AirQuality = HomeApi.Models.AirQuality; + +namespace HomeApi.Extensions; + +public static class ContractExtensions +{ + /// + /// Converts weather related data into a contract. + /// + /// The weather data to map. + /// The name of the location. + /// Optional aurora forecast data. + /// A list of weather forecasts. + /// + /// A object populated with current weather, aurora probability, and forecast information. + /// + public static WeatherInformation ToContract( + this WeatherData weather, + string locationName, + AuroraForecastApiResponse? auroraForecast, + List forecasts) + { + return new WeatherInformation + { + CityName = locationName, + Current = new Models.Current + { + Date = DateTime.Now.ToString(CultureInfo.CurrentCulture), + Feelslike = weather.Current.Feelslike_C, + IsDay = weather.Current.Is_Day, + WindPerMeterSecond = ConvertToMeterPerSecond(weather.Current.Wind_Kph), + WindGustPerMeterSecond = ConvertToMeterPerSecond(weather.Current.Gust_Kph), + Temperature = weather.Current.Temp_C, + LastUpdated = weather.Current.Last_Updated, + Cloud = weather.Current.Cloud, + WindDirection = weather.Current.Wind_Dir, + WeatherDataLocation = new Models.Location + { + Name = weather.Location.Name, + Region = weather.Location.Region, + Country = weather.Location.Country, + Lat = weather.Location.Lat, + Lon = weather.Location.Lon + }, + AirQuality = new AirQuality + { + Co = weather.Current.Air_Quality.Co, // Carbon Monoxide + No2 = weather.Current.Air_Quality.No2, // Nitrogen Dioxide + O3 = weather.Current.Air_Quality.O3, // Ozone + So2 = weather.Current.Air_Quality.So2, // Sulfur Dioxide + Pm10 = weather.Current.Air_Quality.Pm10, // Particulate Matter 10 micrometers or less + Pm2_5 = weather.Current.Air_Quality.Pm2_5, // Particulate Matter 2.5 micrometers or less + }, + AuroraProbability = new Probability + { + Date = auroraForecast.Date, + Calculated = new CalculatedProbability + { + Value = auroraForecast.Probability.Calculated.Value, + Colour = auroraForecast.Probability.Calculated.Colour, + Lat = auroraForecast.Probability.Calculated.Lat, + Long = auroraForecast.Probability.Calculated.Long + }, + Colour = auroraForecast.Probability.Colour, + Value = auroraForecast.Probability.Value, + HighestProbability = new Highest + { + Colour = auroraForecast.Probability.Highest.Colour, + Lat = auroraForecast.Probability.Highest.Lat, + Long = auroraForecast.Probability.Highest.Long, + Value = auroraForecast.Probability.Highest.Value, + Date = auroraForecast.Probability.Highest.Date + } + } + }, + Forecast = forecasts + }; + + double ConvertToMeterPerSecond(double value = 0) + { + if (value > 0) + return value / 3.6; + + return value; + } + } + + public static Models.Forecast ToForecast(this ForecastDay day) + { + return new Models.Forecast + { + Date = day.Date, + MaxTempC = day.Day.Maxtemp_C, + MinTempC = day.Day.Mintemp_C, + DayIcon = day.Day.Condition.Icon, + Astro = new Models.Astro + { + Moon_Illumination = day.Astro.Moon_Illumination, + Moon_Phase = day.Astro.Moon_Phase, + Moonrise = day.Astro.Moonrise, + Moonset = day.Astro.Moonset, + Sunrise = day.Astro.Sunrise, + Sunset = day.Astro.Sunset + }, + Day = ToWeatherSummary(day.Hour.Where(h => h.Is_Day == 1).ToList()), + Night = ToWeatherSummary(day.Hour.Where(h => h.Is_Day == 0).ToList()) + }; + } + + private static WeatherSummary? ToWeatherSummary(List hours) + { + if (hours.Count == 0) + return null; + + return new WeatherSummary + { + ConditionText = hours.GroupBy(h => h.Condition.Text).OrderByDescending(g => g.Count()).First().Key, + ConditionIcon = hours.GroupBy(h => h.Condition.Icon).OrderByDescending(g => g.Count()).First().Key, + AvgTempC = Math.Round(hours.Average(h => h.Temp_C), 1), + AvgFeelslikeC = Math.Round(hours.Average(h => h.Feelslike_C), 1), + TotalChanceOfRain = (int)Math.Round(hours.Average(h => h.Chance_Of_Rain)), + TotalChanceOfSnow = (int)Math.Round(hours.Average(h => h.Chance_Of_Snow)) + }; + } + +} \ No newline at end of file diff --git a/HomeApi/Extensions/IntegrationExtensions.cs b/HomeApi/Extensions/IntegrationExtensions.cs new file mode 100644 index 0000000..881a83e --- /dev/null +++ b/HomeApi/Extensions/IntegrationExtensions.cs @@ -0,0 +1,17 @@ +using HomeApi.Models.Configuration; +using Microsoft.Extensions.Options; + +namespace HomeApi.Extensions; + +public static class IntegrationExtensions +{ + public static void ConfigureBaseAddress(this IHttpClientBuilder builder, + Func getBaseUrl) + { + builder.ConfigureHttpClient((serviceProvider, client) => + { + var config = serviceProvider.GetRequiredService>().Value; + client.BaseAddress = new Uri(getBaseUrl(config)); + }); + } +} \ No newline at end of file diff --git a/HomeApi/Handlers/GetWeather.cs b/HomeApi/Handlers/GetWeather.cs new file mode 100644 index 0000000..2deb672 --- /dev/null +++ b/HomeApi/Handlers/GetWeather.cs @@ -0,0 +1,50 @@ +using HomeApi.Extensions; +using HomeApi.Integration; +using HomeApi.Models; +using HomeApi.Models.Configuration; +using MediatR; +using Microsoft.Extensions.Options; + +namespace HomeApi.Handlers; + +public static class GetWeather +{ + public record Command : IRequest; + + public class Handler : IRequestHandler + { + private readonly ApiConfiguration _apiConfiguration; + private readonly ILogger _logger; + private readonly IGeocodingService _geocodingService; + private readonly IAuroraService _auroraService; + private readonly IWeatherService _weatherService; + + public Handler( + IOptions apiConfiguration, + ILogger logger, + IGeocodingService geocodingService, + IAuroraService auroraService, + IWeatherService weatherService) + { + _apiConfiguration = apiConfiguration.Value; + _logger = logger; + _geocodingService = geocodingService; + _auroraService = auroraService; + _weatherService = weatherService; + } + + public async Task Handle(Command request, CancellationToken cancellationToken) + { + var coordinates = await _geocodingService.GetCoordinatesAsync(_apiConfiguration.DefaultCity); + if (coordinates is null) + throw new Exception("Coordinates not found"); + + var aurora = await _auroraService.GetAuroraForecastAsync(coordinates.Lat, coordinates.Lon); + var weather = await _weatherService.GetWeatherAsync(coordinates.Lat, coordinates.Lon); + + var forecasts = weather.Forecast.Forecastday.Select(day => day.ToForecast()).ToList(); + + return weather.ToContract(coordinates.Name, aurora, forecasts); + } + } +} \ No newline at end of file diff --git a/HomeApi/HomeApi.csproj b/HomeApi/HomeApi.csproj index 3579ed1..cfae6fe 100644 --- a/HomeApi/HomeApi.csproj +++ b/HomeApi/HomeApi.csproj @@ -8,7 +8,10 @@ + + + diff --git a/HomeApi/Integration/AuroraService.cs b/HomeApi/Integration/AuroraService.cs new file mode 100644 index 0000000..52ef175 --- /dev/null +++ b/HomeApi/Integration/AuroraService.cs @@ -0,0 +1,17 @@ +using HomeApi.Integration.Client; +using HomeApi.Models.Response; + +namespace HomeApi.Integration; + +public interface IAuroraService +{ + Task GetAuroraForecastAsync(string lat, string lon); +} + +public class AuroraService(IAuroraClient auroraApi) : IAuroraService +{ + public Task GetAuroraForecastAsync(string lat, string lon) + { + return auroraApi.GetForecastAsync(latitude: lat, longitude: lon); + } +} \ No newline at end of file diff --git a/HomeApi/Integration/Client/AuroraClient.cs b/HomeApi/Integration/Client/AuroraClient.cs new file mode 100644 index 0000000..7f01223 --- /dev/null +++ b/HomeApi/Integration/Client/AuroraClient.cs @@ -0,0 +1,15 @@ +using HomeApi.Models.Response; +using Refit; + +namespace HomeApi.Integration.Client; + +public interface IAuroraClient +{ + [Get("/v1/")] + Task GetForecastAsync( + [AliasAs("type")] string type = "all", + [AliasAs("lat")] string latitude = "0", + [AliasAs("long")] string longitude = "0", + [AliasAs("forecast")] string forecast = "false", + [AliasAs("threeday")] string threeDay = "false"); +} \ No newline at end of file diff --git a/HomeApi/Integration/Client/NominatimClient.cs b/HomeApi/Integration/Client/NominatimClient.cs new file mode 100644 index 0000000..0bef542 --- /dev/null +++ b/HomeApi/Integration/Client/NominatimClient.cs @@ -0,0 +1,13 @@ +using HomeApi.Models.Response; +using Refit; + +namespace HomeApi.Integration.Client; + +public interface INominatimClient +{ + [Get("/search")] + Task> SearchAsync( + [AliasAs("q")] string query, + [AliasAs("format")] string format = "json", + [AliasAs("limit")] int limit = 1); +} \ No newline at end of file diff --git a/HomeApi/Integration/Client/WeatherClient.cs b/HomeApi/Integration/Client/WeatherClient.cs new file mode 100644 index 0000000..bf91a73 --- /dev/null +++ b/HomeApi/Integration/Client/WeatherClient.cs @@ -0,0 +1,17 @@ +using HomeApi.Models.Response; + +namespace HomeApi.Integration.Client; + +using Refit; + +public interface IWeatherClient +{ + [Get("/forecast.json")] + Task GetForecastAsync( + [AliasAs("key")] string apiKey, + [AliasAs("q")] string coordinates, + [AliasAs("days")] int days = 7, + [AliasAs("lang")] string language = "sv", + [AliasAs("aqi")] string aqi = "yes", + [AliasAs("alerts")] string alerts = "yes"); +} diff --git a/HomeApi/Integration/GeocodingService.cs b/HomeApi/Integration/GeocodingService.cs new file mode 100644 index 0000000..34d1e1f --- /dev/null +++ b/HomeApi/Integration/GeocodingService.cs @@ -0,0 +1,19 @@ +using HomeApi.Integration.Client; +using HomeApi.Models.Response; + +namespace HomeApi.Integration; + +public interface IGeocodingService +{ + Task GetCoordinatesAsync(string address); +} + +public class GeocodingService(INominatimClient nominatimApi) : IGeocodingService +{ + public async Task GetCoordinatesAsync(string address) + { + var results = await nominatimApi.SearchAsync(address); + + return results.FirstOrDefault(); + } +} \ No newline at end of file diff --git a/HomeApi/Integration/WeatherService.cs b/HomeApi/Integration/WeatherService.cs new file mode 100644 index 0000000..c1b2caf --- /dev/null +++ b/HomeApi/Integration/WeatherService.cs @@ -0,0 +1,22 @@ +using HomeApi.Integration.Client; +using HomeApi.Models.Configuration; +using HomeApi.Models.Response; +using Microsoft.Extensions.Options; + +namespace HomeApi.Integration; + +public interface IWeatherService +{ + Task GetWeatherAsync(string lat, string lon); +} + +public class WeatherService(IWeatherClient weatherApi, IOptions options) : IWeatherService +{ + private readonly ApiConfiguration _apiConfig = options.Value; + + public Task GetWeatherAsync(string lat, string lon) + { + var location = $"{lat},{lon}"; + return weatherApi.GetForecastAsync(_apiConfig.Keys.Weather, location); + } +} \ No newline at end of file diff --git a/HomeApi/Models/ApiConfiguration.cs b/HomeApi/Models/Configuration/ApiConfiguration.cs similarity index 57% rename from HomeApi/Models/ApiConfiguration.cs rename to HomeApi/Models/Configuration/ApiConfiguration.cs index 5cd7a60..61f3bba 100644 --- a/HomeApi/Models/ApiConfiguration.cs +++ b/HomeApi/Models/Configuration/ApiConfiguration.cs @@ -1,4 +1,4 @@ -namespace HomeApi; +namespace HomeApi.Models.Configuration; public class ApiConfiguration { @@ -10,11 +10,13 @@ public class ApiConfiguration public class BaseUrls { public string Weather { get; set; } = string.Empty; - public string SL { get; set; } = string.Empty; + public string Nominatim { get; set; } = string.Empty; + public string Aurora { get; set; } = string.Empty; } public class Keys { public string Weather { get; set; } = string.Empty; - public string SL { get; set; } = string.Empty; + public string Nominatim { get; set; } = string.Empty; + public string Aurora { get; set; } = string.Empty; } \ No newline at end of file diff --git a/HomeApi/Models/AuroraForecast.cs b/HomeApi/Models/Response/AuroraForecastApiResponse.cs similarity index 96% rename from HomeApi/Models/AuroraForecast.cs rename to HomeApi/Models/Response/AuroraForecastApiResponse.cs index 4813c8a..fc1612b 100644 --- a/HomeApi/Models/AuroraForecast.cs +++ b/HomeApi/Models/Response/AuroraForecastApiResponse.cs @@ -1,10 +1,8 @@ -namespace HomeApi.Models; - -using System; -using System.Collections.Generic; using System.Text.Json.Serialization; -public class AuroraForecast +namespace HomeApi.Models.Response; + +public class AuroraForecastApiResponse { [JsonPropertyName("date")] public DateTime Date { get; set; } diff --git a/HomeApi/Models/Response/NomatimApiResponse.cs b/HomeApi/Models/Response/NomatimApiResponse.cs new file mode 100644 index 0000000..ecf6912 --- /dev/null +++ b/HomeApi/Models/Response/NomatimApiResponse.cs @@ -0,0 +1,8 @@ +namespace HomeApi.Models.Response; + +public class NomatimApiResponse +{ + public string Lat { get; set; } + public string Lon { get; set; } + public string Name { get; set; } +} \ No newline at end of file diff --git a/HomeApi/Models/WeatherApiResponse.cs b/HomeApi/Models/Response/WeatherApiResponse.cs similarity index 99% rename from HomeApi/Models/WeatherApiResponse.cs rename to HomeApi/Models/Response/WeatherApiResponse.cs index 15f8fbe..0045dc8 100644 --- a/HomeApi/Models/WeatherApiResponse.cs +++ b/HomeApi/Models/Response/WeatherApiResponse.cs @@ -1,3 +1,5 @@ +namespace HomeApi.Models.Response; + public class WeatherData { public Location Location { get; set; } @@ -169,4 +171,4 @@ public class Alert public string Expires { get; set; } public string Desc { get; set; } public string Instruction { get; set; } -} +} \ No newline at end of file diff --git a/HomeApi/Models/Home.cs b/HomeApi/Models/WeatherInformation.cs similarity index 59% rename from HomeApi/Models/Home.cs rename to HomeApi/Models/WeatherInformation.cs index fe7906a..3f981da 100644 --- a/HomeApi/Models/Home.cs +++ b/HomeApi/Models/WeatherInformation.cs @@ -1,6 +1,8 @@ +using HomeApi.Models.Response; + namespace HomeApi.Models; -public class Home +public class WeatherInformation { public string CityName { get; set; } = string.Empty; public Current Current { get; set; } = new(); @@ -12,12 +14,27 @@ public class Current public string Date { get; set; } public double Feelslike { get; set; } public int IsDay { get; set; } - public double WindPerHour { get; set; } = new(); - public double WindGustPerHour { get; set; } = new(); - public double Temperature { get; set; } = new(); + public double WindPerMeterSecond { get; set; } = 0; + public double WindGustPerMeterSecond { get; set; } = 0; + public double Temperature { get; set; } = 0; + public string LastUpdated { get; set; } = string.Empty; + public int Cloud { get; set; } + public string WindDirection { get; set; } = string.Empty; + public Location WeatherDataLocation { get; set; } = new(); + public AirQuality AirQuality { get; set; } + public Probability AuroraProbability { get; set; } = new(); } +public class Location +{ + public string Name { get; set; } + public string Region { get; set; } + public string Country { get; set; } + public double Lat { get; set; } + public double Lon { get; set; } +} + public class Probability { public DateTime Date { get; set; } @@ -42,8 +59,8 @@ public class Forecast public double MinTempC { get; set; } public double MaxTempC { get; set; } public string DayIcon { get; set; } - public WeatherSummary Day { get; set; } - public WeatherSummary Night { get; set; } + public WeatherSummary? Day { get; set; } + public WeatherSummary? Night { get; set; } public Astro Astro { get; set; } } public class Astro @@ -56,6 +73,18 @@ public class Astro public double? Moon_Illumination { get; set; } } +public class AirQuality +{ + public double Co { get; set; } + public double No2 { get; set; } + public double O3 { get; set; } + public double So2 { get; set; } + public double Pm2_5 { get; set; } + public double Pm10 { get; set; } + public int Us_Epa_Index { get; set; } + public int Gb_Defra_Index { get; set; } +} + public class WeatherSummary { public string ConditionText { get; set; } diff --git a/HomeApi/Program.cs b/HomeApi/Program.cs index 604d22a..165360f 100644 --- a/HomeApi/Program.cs +++ b/HomeApi/Program.cs @@ -1,17 +1,16 @@ -using HomeApi; +using HomeApi.Registration; using Scalar.AspNetCore; var builder = WebApplication.CreateBuilder(args); -// Add services to the container. builder.Services.AddHttpClient(); +builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining()); builder.Services.AddControllers(); -// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi builder.Services.AddOpenApi(); -builder.Services.Configure(builder.Configuration.GetSection("ApiConfiguration")); +builder.Services.AddIntegration(builder.Configuration); + var app = builder.Build(); -// Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.MapOpenApi(); diff --git a/HomeApi/Registration/RegisterIntegration.cs b/HomeApi/Registration/RegisterIntegration.cs new file mode 100644 index 0000000..78952db --- /dev/null +++ b/HomeApi/Registration/RegisterIntegration.cs @@ -0,0 +1,36 @@ +using HomeApi.Extensions; +using HomeApi.Integration; +using HomeApi.Integration.Client; +using HomeApi.Models.Configuration; +using Microsoft.Extensions.Options; +using Refit; + +namespace HomeApi.Registration; + +public static class RegisterIntegration +{ + public static void AddIntegration(this IServiceCollection services, + IConfiguration configuration) + { + services.Configure(configuration.GetSection("ApiConfiguration")); + + services.AddRefitClient() + .ConfigureHttpClient((sp, client) => + { + var config = sp.GetRequiredService>().Value; + client.BaseAddress = new Uri(config.BaseUrls.Nominatim); + client.DefaultRequestHeaders.Add("User-Agent", "dotnet-geocoder-app"); + }); + + + services.AddRefitClient() + .ConfigureBaseAddress(apiConfiguration => apiConfiguration.BaseUrls.Aurora); + + services.AddRefitClient() + .ConfigureBaseAddress(apiConfiguration => apiConfiguration.BaseUrls.Weather); + + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + } +} \ No newline at end of file diff --git a/HomeApi/appsettings.Development.json b/HomeApi/appsettings.Development.json index 0765307..9e738ac 100644 --- a/HomeApi/appsettings.Development.json +++ b/HomeApi/appsettings.Development.json @@ -11,9 +11,10 @@ "SL": "" }, "BaseUrls": { - "Weather": "https://api.weatherapi.com/v1", - "SL": "NOT CONFIGURED" + "Nominatim": "https://nominatim.openstreetmap.org", + "Aurora": "http://api.auroras.live", + "Weather": "https://api.weatherapi.com/v1" }, "DefaultCity": "Vega stockholms lan" - }, + } } diff --git a/HomeApi/appsettings.json b/HomeApi/appsettings.json index 462274d..a419db2 100644 --- a/HomeApi/appsettings.json +++ b/HomeApi/appsettings.json @@ -11,8 +11,9 @@ "SL": "" }, "BaseUrls": { - "Weather": "https://api.weatherapi.com/v1", - "SL": "NOT CONFIGURED" + "Nominatim": "https://nominatim.openstreetmap.org", + "Aurora": "http://api.auroras.live", + "Weather": "https://api.weatherapi.com/v1" }, "DefaultCity": "Vega stockholms lan" },