Files
BlogPlatform/BlogPlatform/Endpoints/Post/PatchPostIncrementLikeEndpoint.cs
2025-10-17 11:15:05 +02:00

48 lines
1.4 KiB
C#

using BlogPlatform.DTO.Comment.Response;
using BlogPlatform.DTO.Post.Request;
using BlogPlatform.DTO.Post.Response;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
namespace BlogPlatform.Endpoints.Post;
public class PatchPostIncrementLikeEndpoint(BlogPlatformDbContext database) : Endpoint<PatchPostIncrementLikeDto, GetPostDto>
{
public override void Configure()
{
Patch("/api/posts/{@Id}/IncrementLikes", x => new {x.Id});
}
public override async Task HandleAsync(PatchPostIncrementLikeDto req, CancellationToken ct)
{
var post = await database.Posts.SingleOrDefaultAsync(x => x.Id == req.Id, ct);
if (post == null)
{
await Send.NotFoundAsync(ct);
return;
}
post.Likes = post.Likes++;
await database.SaveChangesAsync(ct);
GetPostDto responseDto = new()
{
Id = post.Id,
Title = post.Title,
Content = post.Content,
Likes = post.Likes,
CreatedAt = post.CreatedAt,
UserId = post.UserId,
Comments = post.Comments.Select(c => new GetCommentDto()
{
Id = c.Id,
Content = c.Content,
CreatedAt = c.CreatedAt,
UserId = c.UserId
}).ToList()
};
await Send.OkAsync(responseDto, ct);
}
}