48 lines
1.4 KiB
C#
48 lines
1.4 KiB
C#
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<IActionResult> 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<IActionResult> GetArticles(string hub)
|
|
{
|
|
var cacheKey = $"{hub.ToLower()}:all_articles";
|
|
|
|
var articles = await cache.GetAsync<List<Article>>(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);
|
|
}
|
|
} |