-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathNwsManager.cs
127 lines (109 loc) · 4.71 KB
/
NwsManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
using System.Text.Json;
using System.Web;
using System.Reflection;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.Extensions.Caching.Memory;
using Api.Data;
namespace Api
{
public class NwsManager(HttpClient httpClient, IMemoryCache cache)
{
private static readonly JsonSerializerOptions options = new(JsonSerializerDefaults.Web);
public async Task<Zone[]?> GetZonesAsync()
{
return await cache.GetOrCreateAsync("zones", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
// To get the live zone data from NWS, uncomment the following code and comment out the return statement below.
// This is required if you are deploying to ACA.
//var zones = await httpClient.GetFromJsonAsync<ZonesResponse>("https://api.weather.gov/zones?type=forecast", options);
//return zones?.Features
// ?.Where(f => f.Properties?.ObservationStations?.Count > 0)
// .Select(f => (Zone)f)
// .Distinct()
// .ToArray() ?? [];
// Deserialize the zones.json file from the embedded resource
var assembly = Assembly.GetExecutingAssembly();
var resourceName = "Api.wwwroot.zones.json";
using var stream = assembly.GetManifestResourceStream(resourceName);
if (stream == null)
{
return [];
}
var zones = await JsonSerializer.DeserializeAsync<ZonesResponse>(stream, options);
return zones?.Features
?.Where(f => f.Properties?.ObservationStations?.Count > 0)
.Select(f => (Zone)f)
.Distinct()
.ToArray() ?? [];
});
}
private static int forecastCount = 0;
public async Task<Forecast[]> GetForecastByZoneAsync(string zoneId)
{
// Create an exception every 5 calls to simulate an error for testing
forecastCount++;
if (forecastCount % 5 == 0)
{
throw new Exception("Random exception thrown by NwsManager.GetForecastAsync");
}
var zoneIdSegment = HttpUtility.UrlEncode(zoneId);
var zoneUrl = $"https://api.weather.gov/zones/forecast/{zoneIdSegment}/forecast";
var forecasts = await httpClient.GetFromJsonAsync<ForecastResponse>(zoneUrl, options);
return forecasts
?.Properties
?.Periods
?.Select(p => (Forecast)p)
.ToArray() ?? [];
}
}
}
namespace Microsoft.Extensions.DependencyInjection
{
public static class NwsManagerExtensions
{
public static IServiceCollection AddNwsManager(this IServiceCollection services)
{
services.AddHttpClient<Api.NwsManager>(client =>
{
client.BaseAddress = new Uri("https://api.weather.gov/");
client.DefaultRequestHeaders.Add("User-Agent", "Microsoft - .NET Aspire Demo");
});
services.AddMemoryCache();
// Add default output caching
services.AddOutputCache(options =>
{
options.AddBasePolicy(builder => builder.Cache());
});
return services;
}
public static WebApplication? MapApiEndpoints(this WebApplication app)
{
app.UseOutputCache();
app.MapGet("/zones", async (Api.NwsManager manager) =>
{
var zones = await manager.GetZonesAsync();
return TypedResults.Ok(zones);
})
.CacheOutput(policy => policy.Expire(TimeSpan.FromHours(1)))
.WithName("GetZones")
.WithOpenApi();
app.MapGet("/forecast/{zoneId}", async Task<Results<Ok<Api.Forecast[]>, NotFound>> (Api.NwsManager manager, string zoneId) =>
{
try
{
var forecasts = await manager.GetForecastByZoneAsync(zoneId);
return TypedResults.Ok(forecasts);
}
catch (HttpRequestException)
{
return TypedResults.NotFound();
}
})
.CacheOutput(policy => policy.Expire(TimeSpan.FromMinutes(15)).SetVaryByRouteValue("zoneId"))
.WithName("GetForecastByZone")
.WithOpenApi();
return app;
}
}
}