using Microsoft.AspNetCore.Mvc; using LexWells.Infrastructure.Common.Interfaces; using Microsoft.EntityFrameworkCore; using NewsArchival.Api.Data; using NewsArchival.Core.Models; namespace NewsArchival.Api.Controllers; [ApiController] [Route("api/[controller]")] public class ArticlesController(AppDbContext db, ICacheService cache) : ControllerBase { [HttpPost] public async Task PostArticle([FromBody] Article article) { if (!ModelState.IsValid) return BadRequest(ModelState); db.Articles.Add(article); await db.SaveChangesAsync(); await cache.RemoveAsync($"{article.Category.ToLower()}:all_articles"); return CreatedAtAction( nameof(GetArticles), new { hub = article.Category.ToLower() }, article); } [HttpGet("{hub}")] public async Task GetArticles(string hub) { var cacheKey = $"{hub.ToLower()}:all_articles"; var articles = await cache.GetAsync>(cacheKey); if (articles == null) { articles = await db.Articles .Where(x => x.Category == hub) .OrderByDescending(a => a.CreatedAt) .ToListAsync(); await cache.SetAsync(cacheKey, articles, TimeSpan.FromHours(1)); } return Ok(articles); } }