GeoFeed/AS1024.GeoFeed.Core.WebLogic/GeoFeedRetrurn.cs

72 lines
2.6 KiB
C#

using AS1024.GeoFeed.Core.Interfaces;
using AS1024.GeoFeed.Core.Tools;
using AS1024.GeoFeed.Models;
using Microsoft.Extensions.Caching.Memory;
using System.Text;
namespace AS1024.GeoFeed.Core.WebLogic
{
public class GeoFeedReturn
{
private const string GeoFeedCacheKey = "GeoFeedData";
private const string GeoFeedMimeTypeReturn = "text/csv";
private const string GeoFeedFileName = "geofeed.csv";
private readonly IGeoFeedProvider provider;
private readonly ILogger<GeoFeedReturn> logger;
private readonly IGeoFeedPersistentCacheProvider cacheProvider;
private readonly IMemoryCache memoryCache;
private readonly IWebHostEnvironment environment;
public GeoFeedReturn(IGeoFeedProvider provider,
ILogger<GeoFeedReturn> logger,
IGeoFeedPersistentCacheProvider cacheProvider,
IMemoryCache memoryCache,
IWebHostEnvironment environment)
{
this.provider = provider;
this.logger = logger;
this.cacheProvider = cacheProvider;
this.memoryCache = memoryCache;
this.environment = environment;
}
public async Task<IResult> GetGeoFeed()
{
bool isCached = true;
try
{
if (!memoryCache.TryGetValue(GeoFeedCacheKey, out List<IPGeoFeed>? feed))
{
isCached = false;
feed = await provider.GetGeoFeedDataAsync();
if (environment.IsProduction())
{
MemoryCacheEntryOptions cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromMinutes(15));
memoryCache.Set(GeoFeedCacheKey, feed, cacheEntryOptions);
}
}
return Results.File(Encoding.UTF8.GetBytes(feed.ToGeoFeedCsv(true, isCached)),
GeoFeedMimeTypeReturn,
GeoFeedFileName);
}
catch (HttpRequestException ex)
{
logger.LogWarning($"Temporary failure of retrieving GeoData from upstream. {ex}");
string geoFeedData = cacheProvider.GetGeoFeed();
return Results.File(Encoding.UTF8.GetBytes(geoFeedData),
GeoFeedMimeTypeReturn,
GeoFeedFileName);
}
catch (Exception ex)
{
logger.LogError($"Error: {ex}");
}
return Results.NoContent();
}
}
}