some changes

This commit is contained in:
john 2025-05-17 23:47:19 +02:00
parent 4ec9720541
commit b47bac67ca
37 changed files with 397 additions and 190 deletions

View file

@ -1,4 +1,5 @@
using Femto.Common.Infrastructure.Outbox;
using Femto.Modules.Blog.Domain.Authors;
using Femto.Modules.Blog.Domain.Posts;
using Microsoft.EntityFrameworkCore;
@ -7,6 +8,7 @@ namespace Femto.Modules.Blog.Application;
internal class BlogContext(DbContextOptions<BlogContext> options) : DbContext(options), IOutboxContext
{
public virtual DbSet<Post> Posts { get; set; }
public virtual DbSet<Author> Authors { get; set; }
public virtual DbSet<OutboxEntry> Outbox { get; set; }
protected override void OnModelCreating(ModelBuilder builder)

View file

@ -1,6 +1,11 @@
using Femto.Common.Infrastructure;
using System.Runtime.CompilerServices;
using Femto.Common.Infrastructure;
using Femto.Common.Infrastructure.DbConnection;
using Femto.Common.Infrastructure.Outbox;
using Femto.Common.Integration;
using Femto.Modules.Auth.Contracts.Events;
using Femto.Modules.Blog.Handlers;
using Femto.Modules.Blog.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
@ -14,21 +19,32 @@ public static class BlogStartup
{
public static void InitializeBlogModule(
this IServiceCollection rootContainer,
string connectionString
string connectionString,
IEventBus bus
)
{
var hostBuilder = Host.CreateDefaultBuilder();
hostBuilder.ConfigureServices(services => ConfigureServices(services, connectionString));
hostBuilder.ConfigureServices(services =>
ConfigureServices(services, connectionString, bus)
);
var host = hostBuilder.Build();
rootContainer.AddHostedService(services => new BlogApplication(host));
rootContainer.AddScoped<IBlogModule>(_ => new BlogModule(host));
bus.Subscribe(
(evt, cancellationToken) => EventSubscriber(evt, host.Services, cancellationToken)
);
}
private static void ConfigureServices(this IServiceCollection services, string connectionString)
private static void ConfigureServices(
this IServiceCollection services,
string connectionString,
IEventPublisher publisher
)
{
services.AddTransient<IDbConnectionFactory>(_ => new DbConnectionFactory(connectionString));
@ -46,6 +62,8 @@ public static class BlogStartup
builder.UseLoggerFactory(loggerFactory);
builder.EnableSensitiveDataLogging();
});
services.AddOutbox<BlogContext, OutboxMessageHandler>();
services.AddMediatR(c =>
{
@ -53,5 +71,42 @@ public static class BlogStartup
});
services.ConfigureDomainServices<BlogContext>();
services.AddSingleton(publisher);
}
private static async Task EventSubscriber(
IEvent evt,
IServiceProvider provider,
CancellationToken cancellationToken
)
{
using var scope = provider.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<BlogContext>();
var loggerFactory = scope.ServiceProvider.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<BlogApplication>();
var publisher = scope.ServiceProvider.GetRequiredService<IPublisher>();
// todo inject these
IEventHandler? handler = evt switch
{
UserWasCreatedIntegrationEvent => new UserCreatedEventHandler(
context,
loggerFactory.CreateLogger<UserCreatedEventHandler>()
),
_ => null,
};
if (handler is null)
return;
await handler.Handle(evt, cancellationToken);
if (context.ChangeTracker.HasChanges())
{
await context.EmitDomainEvents(logger, publisher, cancellationToken);
await context.SaveChangesAsync(cancellationToken);
}
}
}

View file

@ -0,0 +1,14 @@
using Femto.Modules.Blog.Domain.Authors;
using Femto.Modules.Blog.Domain.Posts;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Femto.Modules.Blog.Application.Configurations;
internal class AuthorConfiguration : IEntityTypeConfiguration<Author>
{
public void Configure(EntityTypeBuilder<Author> table)
{
table.ToTable("author");
}
}

View file

@ -9,7 +9,5 @@ internal class OutboxEntryConfiguration : IEntityTypeConfiguration<OutboxEntry>
public void Configure(EntityTypeBuilder<OutboxEntry> builder)
{
builder.ToTable("outbox");
builder.Property(x => x.Payload).HasColumnType("jsonb");
}
}

View file

@ -0,0 +1,17 @@
using Femto.Common.Domain;
namespace Femto.Modules.Blog.Domain.Authors;
public class Author : Entity
{
public Guid Id { get; private set; }
public string Username { get; private set; } = null!;
private Author() { }
public Author(Guid userId, string username)
{
this.Id = userId;
this.Username = username;
}
}

View file

@ -4,5 +4,5 @@ using Femto.Common.Integration;
namespace Femto.Modules.Blog.Events;
[EventType("post.created")]
public record PostCreatedIntegrationEvent(Guid EventId, Guid PostId, IEnumerable<Guid> MediaIds)
: IIntegrationEvent;
public record PostCreatedEvent(Guid EventId, Guid PostId, IEnumerable<Guid> MediaIds)
: IEvent;

View file

@ -38,12 +38,9 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Folder Include="Domain\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Femto.Common\Femto.Common.csproj" />
<ProjectReference Include="..\Femto.Modules.Auth.Contracts\Femto.Modules.Auth.Contracts.csproj" />
</ItemGroup>
</Project>

View file

@ -3,9 +3,9 @@ using MediatR;
namespace Femto.Modules.Blog.Handlers;
public class PostCreatedIntegrationEventHandler : INotificationHandler<PostCreatedIntegrationEvent>
public class PostCreatedIntegrationEventHandler : INotificationHandler<PostCreatedEvent>
{
public async Task Handle(PostCreatedIntegrationEvent notification, CancellationToken cancellationToken)
public async Task Handle(PostCreatedEvent notification, CancellationToken cancellationToken)
{
// todo
}

View file

@ -0,0 +1,29 @@
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);
}
}

View file

@ -0,0 +1,22 @@
using Femto.Common.Infrastructure.Outbox;
using Femto.Common.Integration;
using Microsoft.Extensions.Logging;
namespace Femto.Modules.Blog.Infrastructure;
public class OutboxMessageHandler(IEventPublisher publisher, ILogger<OutboxMessageHandler> logger) : IOutboxMessageHandler
{
public async Task HandleMessage<TNotification>(
TNotification notification,
CancellationToken executionContextCancellationToken
)
{
if (notification is IEvent evt)
{
await publisher.Publish(evt);
} else
{
logger.LogWarning("ignoring non IEvent {Type} in outbox message handler", typeof(TNotification));
}
}
}