Files
DS-Cristiano/BlogPlatform/BlogPlatform/Endpoints/User/GetUserEndpoint.cs
2025-10-17 11:44:43 +02:00

71 lines
1.8 KiB
C#

using BlogPlatform.DTO.Comment.Response;
using BlogPlatform.DTO.Post.Response;
using BlogPlatform.DTO.User.Response;
using BlogPlatform.Endpoints.Comment;
using FastEndpoints;
using Microsoft.EntityFrameworkCore;
namespace BlogPlatform.Endpoints.User;
public class GetUserRequest
{
public int Id { get; set; }
}
public class GetUserEndpoint(BlogPlatformDbContext db) : Endpoint<GetUserRequest,GetUserDto>
{
public override void Configure()
{
Get("/api/users/{@id}", x => new{x.Id});
}
public override async Task HandleAsync(GetUserRequest req, CancellationToken ct)
{
Models.User? user = await db.Users.FindAsync(req.Id);
if (user == null)
{
await Send.NotFoundAsync(ct);
return;
}
List<GetPostDto> posts = await db.Posts
.Where(x => x.UserId == req.Id)
.Select(post=> new GetPostDto()
{
Id = post.Id,
Title = post.Title,
Content = post.Content,
Likes = post.Likes,
})
.ToListAsync(ct);
List<GetCommentDto> comments = await db.Comments
.Where(x => x.UserId == req.Id)
.Select(x=> new GetCommentDto()
{
Id = x.Id,
Content = x.Content,
PostId = x.PostId,
})
.ToListAsync(ct);
// Returning the response with DTO
GetUserDto dto = new()
{
Id = user.Id,
Username = user.Username,
Email = user.Email,
Password = user.Password,
Salt = user.Salt,
Comments = comments,
Posts = posts,
};
await Send.OkAsync(dto, ct);
}
}