77 lines
2.1 KiB
C#
77 lines
2.1 KiB
C#
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Extensions.Logging;
|
|
using Robware.Blog;
|
|
using Robware.Data;
|
|
|
|
namespace Robware.Api.Blog.Controllers {
|
|
[ApiController]
|
|
public class BlogController : ControllerBase {
|
|
private const int DefaultPostLimit = 10;
|
|
|
|
private readonly ILogger<BlogController> _logger;
|
|
private readonly IBlogRepository _blogRepository;
|
|
|
|
public BlogController(ILogger<BlogController> logger, IBlogRepository blogRepository) {
|
|
_logger = logger;
|
|
_blogRepository = blogRepository;
|
|
}
|
|
|
|
[HttpGet(nameof(Get) + "/{url}")]
|
|
public async Task<ActionResult<BlogPost>> Get(string url) {
|
|
_logger.Log(LogLevel.Information, $"{nameof(Get)}: {nameof(url)}={url}");
|
|
|
|
try {
|
|
if (int.TryParse(url, out int id)) {
|
|
return await _blogRepository.GetPostByIdAsync(id);
|
|
}
|
|
|
|
return await _blogRepository.GetPostByUrlAsync(url);
|
|
}
|
|
catch (ItemNotFoundException e) {
|
|
_logger.Log(LogLevel.Error, e.Message);
|
|
return NotFound("Could not find blog post");
|
|
}
|
|
}
|
|
|
|
[HttpGet(nameof(GetLatestPosts))]
|
|
public async Task<ActionResult<BlogPost[]>> GetLatestPosts(int count = 0, int offset = 0) {
|
|
_logger.Log(LogLevel.Information, $"{nameof(GetLatestPosts)}: {nameof(count)}={count}, {nameof(offset)}={offset}");
|
|
|
|
if (count <= 0)
|
|
count = DefaultPostLimit;
|
|
|
|
try {
|
|
return (await _blogRepository.GetLatestPostsAsync(count, offset)).ToArray();
|
|
}
|
|
catch (ItemNotFoundException e) {
|
|
_logger.Log(LogLevel.Error, e.Message);
|
|
return NotFound("Could not get latest posts with given parameters");
|
|
}
|
|
}
|
|
|
|
[HttpGet(nameof(GetLatestPost))]
|
|
public async Task<ActionResult<BlogPost>> GetLatestPost() {
|
|
try {
|
|
return await _blogRepository.GetLatestPostAsync();
|
|
}
|
|
catch (ItemNotFoundException e) {
|
|
_logger.Log(LogLevel.Error, e.Message);
|
|
return NotFound("Could not find blog post");
|
|
}
|
|
}
|
|
|
|
//[HttpGet]
|
|
//Task<int> GetCount();
|
|
|
|
//[HttpPost]
|
|
//Task<BlogPost> SavePost(BlogPost post);
|
|
|
|
//[HttpGet]
|
|
//Task<IEnumerable<BlogPost>> GetAllPosts();
|
|
|
|
//[HttpGet]
|
|
//Task DeletePost(int id);
|
|
}
|
|
}
|