Complete the implementation of returning cached data from the local disk cache

This commit is contained in:
Jeff Leung 2024-01-08 10:41:25 -08:00
parent 020db780a6
commit 2d68115f25
1 changed files with 30 additions and 9 deletions

View File

@ -4,6 +4,7 @@ using AS1024.GeoFeed.GeoFeedBuilder;
using Microsoft.Extensions.Caching.Memory;
using AS1024.GeoFeed.Models;
using System.Text;
using AS1024.GeoFeed.GeoFeedLocalCache;
namespace AS1024.GeoFeed.Controllers
{
@ -17,13 +18,16 @@ namespace AS1024.GeoFeed.Controllers
private readonly IMemoryCache memoryCache;
private readonly IWebHostEnvironment environment;
private readonly ILogger<GeofeedController> logger;
private readonly GeoFeedCacheDbContext dbContext;
private const string GeoFeedCacheKey = "GeoFeedData";
public GeofeedController(IGeoFeedProvider builder,
IMemoryCache memoryCache,
IWebHostEnvironment environment,
ILogger<GeofeedController> logger) {
ILogger<GeofeedController> logger,
GeoFeedCacheDbContext dbContext) {
this.logger = logger;
this.dbContext = dbContext;
this.builder = builder;
this.memoryCache = memoryCache;
this.environment = environment;
@ -46,19 +50,36 @@ namespace AS1024.GeoFeed.Controllers
}
}
string csvContent = feed.ToGeoFeedCsv(); // Assuming ToGeoFeedCsv() returns a string in CSV format.
byte[] contentBytes = Encoding.UTF8.GetBytes(csvContent);
string contentType = "text/csv";
return ReturnFile(feed);
} catch (HttpRequestException ex)
{
logger.LogWarning($"Temporary failure of retrieving GeoData from upstream. {ex}");
var results =
dbContext.GeoFeedCacheEntries.ToList();
List<IPGeoFeed> cachedData = [];
results.ForEach(cachedData.Add);
return ReturnFile(cachedData);
}
return new FileContentResult(contentBytes, contentType)
{
FileDownloadName = "geofeed.csv"
};
} catch (Exception ex)
catch (Exception ex)
{
logger.LogError($"Geofeed generation failed. Exception: {ex}");
return StatusCode(500);
}
}
[NonAction]
private IActionResult ReturnFile(List<IPGeoFeed>? feed)
{
string csvContent = feed.ToGeoFeedCsv(); // Assuming ToGeoFeedCsv() returns a string in CSV format.
byte[] contentBytes = Encoding.UTF8.GetBytes(csvContent);
string contentType = "text/csv";
return new FileContentResult(contentBytes, contentType)
{
FileDownloadName = "geofeed.csv"
};
}
}
}