Unify logic of generating the webside unlike a different version we had for MVC and Minimal API

This commit is contained in:
2024-01-18 15:57:01 -08:00
parent 2d95fcb1a1
commit 0c3edd64f3
5 changed files with 89 additions and 128 deletions

View File

@@ -1,4 +1,5 @@
using AS1024.GeoFeed.Core.CacheService;
using AS1024.GeoFeed.Core.GeoFeedLogic;
using AS1024.GeoFeed.Core.GeoFeedPreloader;
using AS1024.GeoFeed.Core.Interfaces;
using AS1024.GeoFeed.Core.Tools;
@@ -18,6 +19,7 @@ namespace AS1024.GeoFeed.MinimalAPI
builder.Services.AddHostedService<GeoFeedCacheService>();
builder.Services.AddHostedService<PreLoadGeoFeed>();
builder.Services.AddTransient<IGeoFeedPersistentCacheProvider, GeoFeedLocalFileCache>();
builder.Services.AddScoped<GeoFeedReturn>();
builder.Services.AddMemoryCache();
builder.Services.AddLogging();
builder.Services.AddHttpClient();
@@ -26,66 +28,15 @@ namespace AS1024.GeoFeed.MinimalAPI
});
var app = builder.Build();
app.Map("/geofeed.csv", async (IGeoFeedProvider provider,
ILogger<Program> logger,
IGeoFeedPersistentCacheProvider cacheProvider,
IMemoryCache memoryCache,
IWebHostEnvironment environment) => {
return await GeoFeedDataRunner(provider, logger, cacheProvider, memoryCache, environment);
});
app.Map("/geofeed.csv", async (GeoFeedReturn feedReturn) => {
return await feedReturn.GetGeoFeed();
});
app.Map("/geofeed", async (IGeoFeedProvider provider,
ILogger<Program> logger,
IGeoFeedPersistentCacheProvider cacheProvider,
IMemoryCache memoryCache,
IWebHostEnvironment environment) => {
return await GeoFeedDataRunner(provider, logger, cacheProvider, memoryCache, environment);
});
app.Map("/geofeed", async (GeoFeedReturn feedReturn) => {
return await feedReturn.GetGeoFeed();
});
app.Run();
}
protected static async Task<IResult> GeoFeedDataRunner(IGeoFeedProvider provider,
ILogger<Program> logger,
IGeoFeedPersistentCacheProvider cacheProvider,
IMemoryCache memoryCache,
IWebHostEnvironment environment)
{
bool isCached = true;
try
{
if (!memoryCache.TryGetValue("GeoFeedData", out List<IPGeoFeed>? feed))
{
isCached = false;
feed = await provider.GetGeoFeedData();
if (environment.IsProduction())
{
MemoryCacheEntryOptions cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(15));
memoryCache.Set("GeoFeedData", feed, cacheEntryOptions);
}
}
return Results.File(Encoding.UTF8.GetBytes(feed.ToGeoFeedCsv(true, isCached)),
"text/csv",
"geofeed.csv");
}
catch (HttpRequestException ex)
{
logger.LogWarning($"Temporary failure of retrieving GeoData from upstream. {ex}");
string geoFeedData = cacheProvider.GetGeoFeed();
return Results.File(Encoding.UTF8.GetBytes(geoFeedData),
"text/csv",
"geofeed.csv");
}
catch (Exception ex)
{
logger.LogError($"Error: {ex}");
}
return Results.NoContent();
}
}
}