oliverbooth.dev/OliverBooth/Pages/Blog/Index.cshtml.cs
Oliver Booth 435a69b27a
perf: add pagination to blog post list
removes the need for API controller accessed via JS
2024-05-05 18:13:06 +01:00

51 lines
1.4 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using OliverBooth.Common.Data.Blog;
using OliverBooth.Common.Services;
namespace OliverBooth.Pages.Blog;
[Area("blog")]
public class Index : PageModel
{
private readonly IBlogPostService _blogPostService;
public Index(IBlogPostService blogPostService)
{
_blogPostService = blogPostService;
}
public IActionResult OnGet([FromQuery(Name = "pid")] Guid? postId = null,
[FromQuery(Name = "p")] int? wpPostId = null)
{
if (postId.HasValue == wpPostId.HasValue)
{
return Page();
}
return postId.HasValue ? HandleNewRoute(postId.Value) : HandleWordPressRoute(wpPostId!.Value);
}
private IActionResult HandleNewRoute(Guid postId)
{
return _blogPostService.TryGetPost(postId, out IBlogPost? post) ? RedirectToPost(post) : NotFound();
}
private IActionResult HandleWordPressRoute(int wpPostId)
{
return _blogPostService.TryGetPost(wpPostId, out IBlogPost? post) ? RedirectToPost(post) : NotFound();
}
private RedirectResult RedirectToPost(IBlogPost post)
{
var route = new
{
year = post.Published.ToString("yyyy"),
month = post.Published.ToString("MM"),
day = post.Published.ToString("dd"),
slug = post.Slug
};
return Redirect(Url.Page("/Blog/Article", route)!);
}
}