62 lines
1.8 KiB
C#
62 lines
1.8 KiB
C#
using System;
|
|
using Svrnty.Sample.Events;
|
|
using Svrnty.Sample.Workflows;
|
|
using Svrnty.CQRS.Events.Abstractions.EventHandlers;
|
|
using Svrnty.CQRS.Events.Abstractions.Models;
|
|
using FluentValidation;
|
|
using Svrnty.CQRS.Abstractions;
|
|
using Svrnty.CQRS.Events.Abstractions;
|
|
|
|
namespace Svrnty.Sample.Commands;
|
|
|
|
public record AddUserCommand
|
|
{
|
|
public string Name { get; set; } = string.Empty;
|
|
public string Email { get; set; } = string.Empty;
|
|
public int Age { get; set; }
|
|
}
|
|
|
|
public class AddUserCommandValidator : AbstractValidator<AddUserCommand>
|
|
{
|
|
public AddUserCommandValidator()
|
|
{
|
|
RuleFor(x => x.Email)
|
|
.NotEmpty()
|
|
.WithMessage("Email is required")
|
|
.EmailAddress()
|
|
.WithMessage("Email must be a valid email address");
|
|
|
|
RuleFor(x => x.Name)
|
|
.NotEmpty()
|
|
.WithMessage("Name is required");
|
|
|
|
RuleFor(x => x.Age)
|
|
.GreaterThan(0)
|
|
.WithMessage("Age must be greater than 0");
|
|
}
|
|
}
|
|
|
|
public class AddUserCommandHandler : ICommandHandlerWithWorkflow<AddUserCommand, int, UserWorkflow>
|
|
{
|
|
public async Task<int> HandleAsync(AddUserCommand command, UserWorkflow workflow, CancellationToken cancellationToken = default)
|
|
{
|
|
// Simulate adding a user
|
|
var userId = new Random().Next(1, 1000);
|
|
|
|
// Emit event via workflow
|
|
// Framework automatically manages EventId, CorrelationId (using workflow.Id), and OccurredAt
|
|
workflow.EmitAdded(new UserAddedEvent
|
|
{
|
|
UserId = userId,
|
|
Name = command.Name,
|
|
Email = command.Email
|
|
});
|
|
|
|
// Could emit multiple events if needed:
|
|
// workflow.EmitAdded(new AnotherUserEvent { ... });
|
|
|
|
// Return just the result - framework handles event emission
|
|
return await Task.FromResult(userId);
|
|
}
|
|
}
|