Files
social-media/src/Web/Features/Contents/Handlers/GetCreatorByAlias.cs
2024-08-06 00:14:40 -04:00

74 lines
2.1 KiB
C#

using FastEndpoints;
using FluentValidation;
using Hutopy.Web.Features.Contents.Data;
using Hutopy.Web.Features.Contents.Handlers.Models;
using Microsoft.EntityFrameworkCore;
namespace Hutopy.Web.Features.Contents.Handlers;
public sealed class GetCreatorByAliasRequest
{
public required string Name { get; set; }
}
public sealed class GetCreatorByAliasRequestValidator
: Validator<GetCreatorByAliasRequest>
{
public GetCreatorByAliasRequestValidator()
{
RuleFor(r => r.Name)
.NotNull().WithMessage("You should specify the Name")
.NotEmpty().WithMessage("You should specify a valid/not empty Name");
}
}
public class GetCreatorByAliasHandler(
ContentDbContext context)
: Endpoint<GetCreatorByAliasRequest, CreatorModel>
{
public override void Configure()
{
Get("/api/creators/@{Name}");
Options((o => o.WithTags("Contents")));
AllowAnonymous();
}
public override async Task HandleAsync(
GetCreatorByAliasRequest req,
CancellationToken ct)
{
var creatorName = req.Name.ToLower();
var creator = await context
.Creators
.Where(c => EF.Functions.Like(c.Name, creatorName))
.FirstOrDefaultAsync(ct);
if (creator is null)
{
await SendNotFoundAsync(ct);
}
else
{
var subscriberCount = await context.Subscriptions.CountAsync(
s => s.CreatorId == creator.Id,
cancellationToken: ct);
var model = new CreatorModel
{
Id = creator.Id,
CreatedBy = creator.CreatedBy,
CreatedAt = creator.CreatedAt,
Name = creator.Name,
About = creator.About,
Socials = creator.Socials,
ProfileColors = creator.ProfileColors,
StoredDataUrls = creator.StoredDataUrls,
SubscriberCount = subscriberCount,
};
await SendAsync(model, cancellation: ct);
}
}
}