using Microsoft.EntityFrameworkCore; using SocialNetwork.Social.Application.Common.Interfaces; using SocialNetwork.Social.Domain.Entities.Feed; namespace WebApi.Endpoints; public class PostEndpoints { public void Map(IEndpointRouteBuilder builder) { builder.MapGet("", GetAllPosts); builder.MapGet("/{postId:guid}", GetPostById); builder.MapPost("", CreatePost); builder.MapPost("/{postId:guid}/comments", CommentPost); builder.MapPost("/{postId:guid}/like", LikePost); } private async Task<IResult> GetAllPosts(IApplicationDbContext dbContext) => Results.Ok(await dbContext.Posts.ToListAsync()); private async Task<IResult> GetPostById(Guid postId, IApplicationDbContext dbContext) { var post = await dbContext.Posts.FindAsync(postId); if (post is null) return Results.NotFound(); return Results.Ok(post); } private async Task<IResult> CommentPost(Guid postId, Comment comment, IApplicationDbContext dbContext) { var post = await dbContext.Posts.FindAsync(postId); if (post is null) return Results.NotFound(); comment.PostId = postId; post.Comments.Add(comment); await dbContext.SaveChangesAsync(default); return Results.CreatedAtRoute("api/posts/{id}", new {id = postId}, comment); } private async Task<IResult> CreatePost(Post post, IApplicationDbContext dbContext) { var doesPostExist = await dbContext.Posts.AnyAsync(p => p.Id == post.Id); if (doesPostExist) return Results.Conflict(); var entry = dbContext.Posts.Add(post); await dbContext.SaveChangesAsync(default); var persistedPost = entry.Entity; return Results.Created($"/api/posts/{persistedPost.Id}", persistedPost); } private async Task<IResult> LikePost(Guid postId, Guid likerId, IApplicationDbContext dbContext) { var post = await dbContext.Posts.FindAsync(postId); if (post is null) return Results.NotFound(); post.LikesCount++; // TODO add who liked the post await dbContext.SaveChangesAsync(default); return Results.Ok(); } }