Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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();
}
}