2021-12-14 16:06:36 +01:00

93 lines
2.4 KiB
C#

using System.ComponentModel.DataAnnotations;
using HackerNet.Application;
using HackerNet.Infrastructure.AspNet.Filters;
using Microsoft.AspNetCore.Mvc;
namespace HackerNet.Api.Controllers;
[ApiController]
[Route("/api/links")]
public class LinksController : ControllerBase
{
private readonly LinkService _linkService;
public LinksController(LinkService linkService)
{
_linkService = linkService;
}
/// <summary>
/// Retourne les derniers liens publiés de la plateforme.
/// </summary>
/// <returns></returns>
[HttpGet]
public ActionResult<LinkHomePage[]> GetLinks()
{
return _linkService.GetPublishedLinks();
}
/// <summary>
/// Récupère un lien par son identifiant.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("{id:guid}")] // https://docs.microsoft.com/fr-fr/aspnet/core/fundamentals/routing?view=aspnetcore-6.0#route-constraint-reference
[CustomExceptionFilter]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<LinkHomePage> GetLinkDetail(Guid id)
{
return _linkService.GetLinkDetail(id);
}
/// <summary>
/// Récupère les commentaires associés au lien.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("{id:guid}/comments")]
public ActionResult<LinkComment[]> GetLinkComments(Guid id)
{
return _linkService.GetLinkComments(id);
}
[HttpPost("{id:guid}/comments")]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult PublishComment(Guid id, PublishCommentBody cmd)
{
var commentId = _linkService.PublishComment(new PublishCommentCommand
{
LinkId = id,
Content = cmd.Content
});
return CreatedAtAction(
nameof(CommentsController.GetById),
"Comments",
new { id = commentId },
null
);
}
/// <summary>
/// Publie un nouveau lien sur la plateforme
/// </summary>
/// <param name="cmd"></param>
/// <returns></returns>
[HttpPost]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status201Created)]
public ActionResult PublishLink(PublishLinkCommand cmd)
{
var id = _linkService.PublishLink(cmd);
return CreatedAtAction(nameof(GetLinkDetail), new { id = id }, null);
}
}
public class PublishCommentBody
{
[Required]
public string Content { get; set; }
}