femto-backend/Femto.Modules.Blog/Handlers/UserCreatedEventHandler.cs
2025-05-17 23:47:19 +02:00

29 lines
No EOL
1.1 KiB
C#

using Femto.Modules.Auth.Contracts.Events;
using Femto.Modules.Blog.Application;
using Femto.Modules.Blog.Domain.Authors;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace Femto.Modules.Blog.Handlers;
internal class UserCreatedEventHandler(BlogContext context, ILogger<UserCreatedEventHandler> logger) : Common.Integration.EventHandler<UserWasCreatedIntegrationEvent>
{
protected override async Task Handle(UserWasCreatedIntegrationEvent evt, CancellationToken cancellationToken)
{
if (await context.Authors.AnyAsync(x => x.Username == evt.Username, cancellationToken))
{
logger.LogError("can't create author: author with username {Username} already exists", evt.Username);
return;
}
if (await context.Authors.AnyAsync(x => x.Id == evt.UserId, cancellationToken))
{
logger.LogError("can't create author: author with id {UserId} already exists", evt.UserId);
return;
}
var author = new Author(evt.UserId, evt.Username);
await context.Authors.AddAsync(author, cancellationToken);
}
}