Skip to content

Commit

Permalink
Added initial caching.
Browse files Browse the repository at this point in the history
  • Loading branch information
robpearson committed Feb 21, 2024
1 parent 05a4dfe commit e1d5d03
Showing 1 changed file with 17 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using OctopusSamples.ProductService.Models;
Expand All @@ -13,6 +14,7 @@ namespace OctopusSamples.ProductService.Controllers
public class ProductsController : ControllerBase
{
private readonly IProductRepository _productRepository;
private readonly IList<ProductDetail> _productCache = new List<ProductDetail>();

public ProductsController(IProductRepository productRepository)
{
Expand All @@ -21,22 +23,33 @@ public ProductsController(IProductRepository productRepository)

[HttpGet]
public async Task<ActionResult<List<ProductDetail>>> GetAllAsync()
{
{
return await _productRepository.GetAll();
}

[HttpGet("{id}")]
[ProducesResponseType(404)]
public async Task<ActionResult<ProductDetail>> GetByIdAsync(int id)
{
var pet = await _productRepository.GetById(id);
ProductDetail product = null;

var cachedProduct = _productCache.FirstOrDefault(x => x.Id == id);

if (cachedProduct != null)
{
product = cachedProduct;
}
else
{
product = await _productRepository.GetById(id);
}

if (pet == null)
if (product == null)
{
return NotFound();
}

return pet;
return product;
}
}
}

0 comments on commit e1d5d03

Please sign in to comment.