From 2d68115f2543386d0b8e7ff476bd4b41b48d7a99 Mon Sep 17 00:00:00 2001 From: Jeff Leung Date: Mon, 8 Jan 2024 10:41:25 -0800 Subject: [PATCH] Complete the implementation of returning cached data from the local disk cache --- .../Controllers/GeofeedController.cs | 39 ++++++++++++++----- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/AS1024.GeoFeed/Controllers/GeofeedController.cs b/AS1024.GeoFeed/Controllers/GeofeedController.cs index a0c3fa0..3d58028 100644 --- a/AS1024.GeoFeed/Controllers/GeofeedController.cs +++ b/AS1024.GeoFeed/Controllers/GeofeedController.cs @@ -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 logger; + private readonly GeoFeedCacheDbContext dbContext; private const string GeoFeedCacheKey = "GeoFeedData"; public GeofeedController(IGeoFeedProvider builder, IMemoryCache memoryCache, IWebHostEnvironment environment, - ILogger logger) { + ILogger 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 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? 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" + }; } } }