add 4-hr in-memory cache for key endpoints

ref #332
This commit is contained in:
Collin M. Barrett 2018-08-12 17:23:26 -05:00
parent 39446e1d3e
commit e03bc675d3
3 changed files with 27 additions and 5 deletions

View file

@ -15,6 +15,7 @@ public static class ConfigureServicesCollection
public static void AddFilterListsApi(this IServiceCollection services)
{
services.ConfigureCookiePolicy();
services.AddMemoryCache();
services.AddMvcCustom();
services.AddRoutingCustom();
services.AddApiVersioning();

View file

@ -1,5 +1,7 @@
using FilterLists.Services.Seed;
using System;
using FilterLists.Services.Seed;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
namespace FilterLists.Api.V1.Controllers
{
@ -8,6 +10,8 @@ namespace FilterLists.Api.V1.Controllers
[Route("v{version:apiVersion}/[controller]")]
public class BaseController : Controller
{
protected readonly TimeSpan AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(4);
protected readonly IMemoryCache MemoryCache;
protected readonly SeedService SeedService;
public BaseController()
@ -15,5 +19,11 @@ public BaseController()
}
protected BaseController(SeedService seedService) => SeedService = seedService;
protected BaseController(IMemoryCache memoryCache, SeedService seedService)
{
MemoryCache = memoryCache;
SeedService = seedService;
}
}
}

View file

@ -4,6 +4,7 @@
using FilterLists.Services.Seed;
using FilterLists.Services.Seed.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
namespace FilterLists.Api.V1.Controllers
{
@ -11,16 +12,26 @@ public class ListsController : BaseController
{
private readonly FilterListService filterListService;
public ListsController(SeedService seedService, FilterListService filterListService) : base(seedService) =>
this.filterListService = filterListService;
public ListsController(IMemoryCache memoryCache, SeedService seedService, FilterListService filterListService) :
base(memoryCache, seedService) => this.filterListService = filterListService;
[HttpGet]
public async Task<IActionResult> Index() => Json(await filterListService.GetAllSummariesAsync());
public async Task<IActionResult> Index() =>
Json(await MemoryCache.GetOrCreate("ListsController_Index", entry =>
{
entry.AbsoluteExpirationRelativeToNow = AbsoluteExpirationRelativeToNow;
return filterListService.GetAllSummariesAsync();
}));
[HttpGet]
[Route("{id}")]
//TODO: respond with appropriate exception if negative id queried
public async Task<IActionResult> GetById(int id) => Json(await filterListService.GetDetailsAsync((uint) id));
public async Task<IActionResult> GetById(int id) =>
Json(await MemoryCache.GetOrCreate("ListsController_GetById_" + id, entry =>
{
entry.AbsoluteExpirationRelativeToNow = AbsoluteExpirationRelativeToNow;
return filterListService.GetDetailsAsync((uint)id);
}));
[HttpGet("seed")]
public async Task<IActionResult> Seed() => Json(await SeedService.GetAllAsync<FilterList, FilterListSeedDto>());