65 lines
1.9 KiB
C#
65 lines
1.9 KiB
C#
using BeReadyBackend.Models;
|
|
using BeReadyBackend.Repositories;
|
|
using BeReadyBackend.Services;
|
|
using BeReadyBackend.Specifications.Posts;
|
|
using BeReadyBackend.Specifications.Users;
|
|
using FastEndpoints;
|
|
|
|
namespace BeReadyBackend.Endpoints.Posts;
|
|
|
|
public class PatchLikeRequest
|
|
{
|
|
public int PostId { get; set; }
|
|
}
|
|
|
|
public class PatchLikeEndpoint(UserPostsRepository userPostsRepository, UsersRepository usersRepository, UserService userService, PostsRepository postsRepository)
|
|
: Endpoint<PatchLikeRequest>
|
|
{
|
|
public override void Configure()
|
|
{
|
|
Patch("/Posts/{@PostId}/Like", x => new { x.PostId });
|
|
Description(x => x.Accepts<PatchLikeRequest>());
|
|
}
|
|
|
|
public override async Task HandleAsync(PatchLikeRequest req, CancellationToken ct)
|
|
{
|
|
int userId = userService.GetUserIdFromToken();
|
|
|
|
Post? post = await postsRepository.SingleOrDefaultAsync(new GetPostByIdSpec(req.PostId), ct);
|
|
if (post is null)
|
|
{
|
|
await Send.NotFoundAsync(ct);
|
|
return;
|
|
}
|
|
|
|
User? user = await usersRepository.SingleOrDefaultAsync(new GetUserByIdSpec(userId), ct);
|
|
if (user is null)
|
|
{
|
|
await Send.NotFoundAsync(ct);
|
|
return;
|
|
}
|
|
|
|
UserPost? userPost = await userPostsRepository.SingleOrDefaultAsync(new GetUserPostByIdsSpec(userId, req.PostId), ct);
|
|
if (userPost is not null)
|
|
{
|
|
post.Likes = Math.Max(0, post.Likes - 1);
|
|
post.User!.TotalLikes = Math.Max(0, post.User.TotalLikes - 1);
|
|
|
|
await userPostsRepository.DeleteAsync(userPost, ct);
|
|
await Send.NoContentAsync(ct);
|
|
return;
|
|
}
|
|
|
|
post.Likes++;
|
|
post.User!.TotalLikes++;
|
|
|
|
UserPost liked = new()
|
|
{
|
|
UserId = userId,
|
|
PostId = req.PostId
|
|
};
|
|
|
|
await userPostsRepository.AddAsync(liked, ct);
|
|
await Send.NoContentAsync(ct);
|
|
}
|
|
} |