|
|
|
using backend.Models;
|
|
|
|
using backend.Services;
|
|
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
|
|
|
namespace backend.Controllers;
|
|
|
|
[ApiController]
|
|
|
|
[Route("blog/api/[controller]")]
|
|
|
|
public class BlogPostController: ControllerBase
|
|
|
|
{
|
|
|
|
private readonly BlogPostService _blogPostService;
|
|
|
|
|
|
|
|
public BlogPostController(BlogPostService blogPostService)
|
|
|
|
{
|
|
|
|
_blogPostService = blogPostService;
|
|
|
|
}
|
|
|
|
|
|
|
|
[HttpGet]
|
|
|
|
public async Task<List<BlogPost>> Get() =>
|
|
|
|
await _blogPostService.GetAllPostsAsync();
|
|
|
|
|
|
|
|
[HttpGet("{id:length(24)}")]
|
|
|
|
public async Task<BlogPost?> Get(string id) =>
|
|
|
|
await _blogPostService.GetPostAsync(id);
|
|
|
|
|
|
|
|
[HttpGet("newest/{n}")]
|
|
|
|
public async Task<List<BlogPost>> GetLast(int n) =>
|
|
|
|
await _blogPostService.GetLastNPostsAsync(n);
|
|
|
|
|
|
|
|
[Authorize]
|
|
|
|
[HttpPost]
|
|
|
|
public async Task<IActionResult> Post([FromBody]BlogPost post)
|
|
|
|
{
|
|
|
|
await _blogPostService.CreatePostAsync(post);
|
|
|
|
return CreatedAtAction(nameof(Get), new {id = post.Id}, post);
|
|
|
|
}
|
|
|
|
|
|
|
|
[HttpPut("{id:length(24)}")]
|
|
|
|
public async Task<IActionResult> Put(string id, [FromBody]BlogPost post)
|
|
|
|
{
|
|
|
|
var postToUpdate = await _blogPostService.GetPostAsync(id);
|
|
|
|
if (postToUpdate == null)
|
|
|
|
{
|
|
|
|
return NotFound();
|
|
|
|
}
|
|
|
|
await _blogPostService.UpdatePostAsync(id, post);
|
|
|
|
return NoContent();
|
|
|
|
}
|
|
|
|
|
|
|
|
[HttpDelete("{id:length(24)}")]
|
|
|
|
public async Task<IActionResult> Delete(string id)
|
|
|
|
{
|
|
|
|
var postToDelete = await _blogPostService.GetPostAsync(id);
|
|
|
|
if (postToDelete == null)
|
|
|
|
{
|
|
|
|
return NotFound();
|
|
|
|
}
|
|
|
|
await _blogPostService.DeletePostAsync(id);
|
|
|
|
return NoContent();
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|